Hacking Web Applications

advertisement
In this chapter, we will learn about Web applications, Web application components, and working
of Web applications, and discuss about hidden field manipulation, cross-site scripting (XSS), and
Web services attacks. This chapter focuses on identifying Web application hacking and Web
application security tools. This chapter covers Web application firewalls and gains insights on
Web application pen testing.
13.1 Understand Web applications, Web application components, and working of Web
applications
Exam Focus: Understand Web applications, Web application components, and working of Web
applications. Objective includes:



Understand Web applications.
Identify Web application components.
Understand working of Web applications.
Web application
A Web application consists of an Internet Information Services (IIS) site with a unique
application pool. When a user creates a new Web application, he also creates a new database and
defines the authentication method used to connect to the database. A Web application must be
created first before creating a site or a site collection.
Features of Web applications
The primary features of Web applications are as follows:





Web applications need only Web browsers to run applications.
Web applications require very little space on client computers.
Web applications do not require any upgrade. Upgrades run on the server and are
automatically delivered to users.
Web applications integrate themselves easily with various server-side Web procedures,
such as email and searching.
Web applications provide cross-platform compatibility.
Web application security statistics
The following are the Web application security statistics:
Web application vulnerabilities Percent
Cross-site scripting
80 %
SQL injection
62 %
Parameter tampering
60 %
Cookie poisoning
37 %
Database Server
33 %
Web Server
23 %
Buffer overflow
19 %
Components of Web applications
The main components of Web applications are as follows:










Login
Web server
Session tracking mechanism
User permissions
Application content
Data access
Data store
Role-level system security
Application logic
Logout
Working of Web applications
The following image shows the working of Web applications:
13.2 Understand Web application architecture, parameter/form tampering, and injection flaws
Exam Focus: Understand Web application architecture, parameter/form tampering, and injection
flaws. Objective includes:



Examine Web application architecture.
Assess parameter/form tampering.
Understand injection flaws.
Web application architecture
The following is the Web application architecture:
Web applications consist of four important components:




Clients: The end users of Web applications.
Business layer: The business layer contains the functional algorithms that handle
information exchange between a database and a user interface.
Web server: A type of server that makes a Website available on the Internet and
manages the interaction and HTTP exchanges in the background. It supplies static
content to a Web browser by loading a file(s) from disk and sending it via the network to
the end user's Web browser since the Website is on the Internet, management is done by a
Web server. The browser and the server interact with each other using HTTP.
Database layer: The database layer is responsible for the storing, retrieval, and integrity
of user data for the Web application.
Web attack vectors
An attack vector is a path or means that an attacker can use to gain access to computer or
network resources. The attacker can use the attack vector to deliver an attack payload or cause a
malicious outcome. Attack vectors include the following:






Parameter manipulation
XML poisoning
Client validation
Server misconfiguration
Web service routing issues
Cross-site scripting
As the attack vectors keep changing and evolving with new technological evolution, no
protection method is completely attack-proof.
Vulnerability stack
Enterprise security professionals deal with vulnerabilities. They have to solve as many issues as
possible wherever they appear. To focus for vulnerability scanning/ assessment solutions,
vulnerability stack is used. The following is the vulnerability stack:
Web applications threats - 1
The following are Web applications threats - 1:













Cookie poisoning
Insecure storage
Information leakage
Improper error handling
Broken account management
Directory traversal
SQL injection
Parameter/form tampering
Denial of Service
Buffer overflow
Log tampering
Unvalidated input
Cross site scripting (XSS)





Injection flaws
Cross site request forgery
Broken access control
Security misconfiguration
Broken session management
Web application threats - 2
The following are Web application threats - 2:
















Platform exploits
Insecure direct object references
Insufficient transport layer protection
Failure to restrict URL access
Insecure cryptographic storage
Cookie snooping
Obfuscation application
DMZ protocol attacks
Security management exploits
Authentication hijacking
Network access attacks
Web services attacks
Hidden manipulation
Unvalidated redirects and forwards
Session fixation attack
Malicious file extension
Unvalidated input
Input validation flaws refer to Web application vulnerabilities where validation of input from a
client does not take place before Web applications and backend servers process it. Attackers
exploit input validation flaws so that they can perform cross-site scripting, buffer overflow,
injection attacks, etc. that lead to data theft and system malfunctioning.
Parameter/form tampering attack
In a parameter/form tampering attack, the attacker modifies the hidden field values of the form
and changes data. This attack can cause theft of services, escalation of access, and session
hijacking. The following are countermeasures against parameter/form tampering attacks:


Field validity checking
Minimizing the use of hidden parameters
Directory traversal
Directory traversal (or path traversal) is an attacking method to exploit insufficient security
validation/sanitization of user-supplied input file names, so that characters representing "traverse
to parent directory" are passed through to the file APIs.
The goal of this attack is to order an application to access a computer file that is not intended to
be accessible. This attack exploits a lack of security (the software is acting exactly as it is
supposed to) as opposed to exploiting a bug in the code. Directory traversal is also known as the
'../' (dot dot slash) attack, directory climbing, and backtracking. Some forms of this attack are
also canonicalization attacks.
Security misconfiguration
Attackers gain unauthorized access to default accounts, read unused pages, exploit unpatched
flaws, and read or write unprotected files and directories, etc. by using misconfiguration
vulnerabilities. Server misconfiguration can take place at any level of an application attack,
including the following:





Platform
Web server
Application server
Framework
Custom code
The following are server configuration problems:




Server software flaws
Enabling unnecessary services
Improper authentication
Unpatched security flaws
Injection flaws
Injection flaws are the vulnerabilities where a foreign agent illegally uses a sub-system. They are
the vulnerability holes that can be used to attack applications. It is the most common technique
of attacking a database. Injection occurs when user-supplied data is sent to an interpreter as part
of a command or query. The attacker's hostile data tricks the interpreter into executing
involuntary commands or changing data. Injection flaws include XSS (HTML Injection) and
SQL Injection.
In SQL injection, malicious SQL queries are injected into user input methods. In command
injection, malicious code is injected via a Web application. In LDAP injection, malicious LDAP
statements are injected.
The following are countermeasures against injection flaws attacks:




Avoid accessing external interpreters wherever possible and use library API's.
Use prepared statement or stored procedures to overcome the SQL injection attack.
Ensure that the Web application runs only with minimum privileges.
Validate data while making calls to backend databases.
SQL injection attacks
SQL injection attacks use a series of malicious SQL queries for direct manipulation of the
database. To bypass normal security measures and access the valuable data, an attacker can use a
vulnerable Web application. SQL injection attacks are generally executed from the address bar,
from within application fields, and via queries and searches.
Command injection attacks
The following are command injection attacks:



Shell injection: In order to gain shell access to a webserver, an attacker attempts to craft
an input string. The following are shell injection functions:
o system()
o StartProcess()
o java.lang.Runtime.exec()
o System.Diagnostics.Process.Start()
HTML embedding: This attack is used to deface Websites virtually. In this attack, an
attacker appends an extra HTML-based content to the vulnerable Web application.
Without checking for HTML code or scripting, user input to a Web script is placed into
the output HTML in HTML embedding attacks.
File injection: In this attack, an attacker exploits the vulnerability and adds malicious
code into system files.
LDAP injection
An LDAP injection technique takes advantage of non-validated Web application input
vulnerabilities in order to pass LDAP filters. LDAP filters are used to search Directory Services
in order to obtain direct access to databases behind an LDAP tree.
Working of LDAP injection
LDAP injection attacks are like SQL injection attacks. But, LDAP injection attacks generate
LDAP query by exploiting user parameters. Send a query to the server that generates an invalid
input to test if an application is vulnerable to LDAP code injection. The LDAP server can be
exploited with code injection techniques if the LDAP server returns an error.
Cross-site request forgery (CSRF) attacks
Cross-site request forgery, also known as a one-click attack or session riding, is a type of
malicious exploit of a Website whereby unauthorized commands are transmitted from a user that
the Website trusts. Unlike cross-site scripting (XSS), which exploits the trust a user has for a
particular site, CSRF exploits the trust that a site has in a user's browser. The attack works by
including a link or script in a page that accesses a site to which the user is known to have
authenticated.
Working of cross-site request forgery (CSRF) attacks
Cross-site request forgery (CSRF) attacks include the following steps:
1. A user uses his credentials to login to the trusted server.
2. The server sets a session cookie in the user's browser.
3. An attacker sends a phishing mail to trick a user and asks him to send a request to a
malicious site.
4. The user requests a page from the malicious server. The response page includes malicious
code. Malicious code is executed in the trusted server.
Web application Denial of Service attack
Attackers send hundreds of resource-intensive requests, such as pulling out large image files or
requesting dynamic pages that need expensive search operations on the backend database servers
in order to exhaust available server resources. Applications are vulnerable due to reasonable use
of expectations, application environment bottlenecks, implementation flaws, and poor data
validation. The following are the targets of attackers in Denial of Service attacks:




CPU, memory, and sockets
Disk bandwidth
Database bandwidth
Worker processes
Existing DoS protection measures are unable to detect application-level DoS attacks, as
application-level DoS attacks emulate the same request syntax and network-level traffic
characteristics as that of the legitimate clients.
Examples of Denial of Service
The following are examples of Denial of Service:




Login attacks: An attacker continually sends login requests that require the presentation
tier to access the authentication mechanism. This may overload the login process and
make it unavailable or unreasonably slow to respond.
Account lock-out attacks: An attacker may enumerate usernames via another
vulnerability in the application and then use valid usernames and incorrect passwords to
authenticate to the site. After the specified number of failed attempts, the use of invalid
passwords will lock out the accounts. This will prevent legitimate users from using the
site.
User enumeration: An attacker can automate the process of attempting common
usernames from a dictionary file to enumerate the user of the application if the
application states which part of the username/ password pair is incorrect.
User registration DoS: An attacker can create a program that submits the registration
form repeatedly. This adds a large number of spurious users to the application.
Buffer overflow attack
Buffer overflow is a condition in which an application receives more data than it is configured to
accept. It helps an attacker not only to execute a malicious code on the target system but also to
install backdoors on the target system for further attacks. The attacker modifies function pointers
used by an application in order to direct program execution via a jump or call instruction and
point it to a location in the memory including malicious codes. All buffer overflow attacks are
due to only sloppy programming or poor memory management by the application developers.
Cookie poisoning
In cookie poisoning, an attacker modifies the value of cookies before sending them back to the
server. On modifying the cookie values, the attacker can log in to any other user account and can
perform identity theft. The following figure explains how cookie poisoning occurs:
For example: The attacker visits an online shop that stores the IDs and prices of the items to buy
in a cookie. After selecting the items that he wants to buy, the attacker changes the price of the
item to 1.
Original cookie values: ItemID1 = 2ItemPrice1 = 900ItemID2 = 1ItemPrice2 = 200
Modified cookie values: ItemID1 = 2ItemPrice1 = 1ItemID2 = 1ItemPrice2 = 1Now, the
attacker clicks the Buy button and the prices are sent to the server that calculates the total price.
Another use of a cookie poisoning attack is to pretend to be another user after changing the
username in the cookie values:
Original cookie values: LoggedIn = TrueUsername = Mark
Modified cookie values: LoggedIn = TrueUsername = AdminNow, after modifying the cookie
values, the attacker can do the admin login.
Working of cookie poisoning
Cookie poisoning includes the following steps:
1.
2.
3.
4.
5.
A user browses a Web page.
Webserver replies with the requested page.
Webserver sets a cookie on the user's browser.
An attacker steals the cookie by using sniffing, XSS, and phishing attacks.
An attacker uses modified cookie and then orders a product. The delivery of the product
is made to the attacker's address.
Session fixation
In session fixation attacks, the attacker attempts to exploit the vulnerability of a system by
fixating another person's session identifier (SID). Session fixation attacks are achieved by
creating a link to an application and appending the session identifier that the attacker wishes to
give any user clicking the link.
<a href="http://php.org/index.php?PHPSESSID=14">Click here</a>
When a user accesses the developer's site through this session, he may provide sensitive
information and login credentials. With such information, the attacker may ride on the same
session and gain access to the user's account.
The following example involves the use of a session fixation attack:
1.
2.
3.
4.
5.
6.
An attacker uses his credentials to log on to the bank Website.
Webserver sets a session ID on the machine of the attacker.
The attacker sends an email including a link with a fixed session ID.
A user is redirected to the bank Website when he clicks the link.
The user uses his credentials and fixed session ID to log on to the server.
The attacker uses the victim's credentials with the same session ID to log on to the server.
Insufficient transport layer protection
Weak algorithms are supported, and expired or invalid certificates are used by insufficient
transport layer protection. An attacker can use unprivileged SSL setup in order to launch
phishing and MITM attacks. Insufficient transport layer protection exposes user's data to
untrusted third parties and can result in account theft.
Improper error handling
Improper error handling provides insight into source code such as logic flaws, default accounts,
etc. An attacker identifies vulnerabilities by using the information received from an error
message.
Insecure cryptographic storage
In insecure cryptography storage, an application securely encrypts and stores sensitive data in the
database by using poorly written encryption code. An attacker can steal or modify weakly
protected data such as credit cards, SSNs, and other authentication credentials.
Broken authentication and session management
The following vulnerabilities in the authentication or session management are used by an
attacker to impersonate users:




Exposed accounts
Session IDs
Logout
Password management




Timeouts
Remember me
Secret question
Account update
The attacker sniffs the network traffic or obtains the session IDs by tricking the user, and reuses
the session IDs for malicious purposes.
The attacker can exploit a user's privileges by using the same browser later if an application's
timeouts are not set properly and the user does not log out from sites accessed through a public
computer when he closes the browser.
An attacker can access the Web application's password database. The attacker can exploit every
user's password if user passwords are not encrypted.
Unvalidated redirects and forwards
Attackers use unvalidated redirects to install malware or trick users to disclose passwords or
other sensitive information. Unsafe forwards by a user can allow the attacker to bypass access
control.
Unvalidated redirect
Unvalidated forward
13.3 Discuss hidden field manipulation, cross-site scripting (XSS), and Web services attacks
Exam Focus: Discuss hidden field manipulation, cross-site scripting (XSS), and Web services
attacks. Objective includes:



Discuss hidden field manipulation attacks.
Describe cross-site scripting (XSS) attacks.
Understand Web services attacks.
Hidden field manipulation attack
The selection is typically stored as form field values and sent to the application as an HTTP
request when a user makes selections on an HTML page. HTML can also store field values as
Hidden Fields. The browser does not render Hidden Fields to the screen. During form
submissions, Hidden Fields are collected and submitted as parameters. Attackers can examine
the HTML code of the page and change post requests to server by changing the hidden field
values.
Cross-site scripting attack
A cross-site scripting attack is one in which an attacker enters malicious data into a Website. For
example, the attacker posts a message that contains malicious code to any newsgroup site. When
another user views this message, the browser interprets this code and executes it and, as a result,
the attacker is able to take control of the user's system. Cross-site scripting attacks require the
execution of client-side languages such as JavaScript, Java, VBScript, ActiveX, Flash, etc.
within a user's Web environment. With the help of a cross-site scripting attack, the attacker can
perform cookie stealing, sessions hijacking, etc.
The following scenario involves the use of a cross-site scripting attack:
1. An attacker sends an email with a malicious link. The email includes a message that a
user has won a lottery and needs to click a given link in order the claim the lottery.
2. The user clicks the malicious link. The legitimate server receives the request.
3. The server sends a page to the user with the client profile. Malicious code is executed on
the client's Web server.
4. The attacker gets access to the victim's computer.
The following is an example of an XSS attack in blog posting:
1. An attacker adds a malicious script in the comment field of the blog post. The comment
with the malicious link is stored on the server.
2. When a user visits the Website, he is redirected to the malicious Website.
Working of a cross site scripting (XSS) attack
A cross site scripting attack works in the following manner:




The attacker identifies a Web site that has one or more XSS bugs. For example, a Web
site that echoes the contents of a query string.
The attacker crafts a special URL that includes a malformed and malicious query string
containing HTML and scripts such as JavaScript.
The attacker finds a victim and gets the victim to click on a link that includes the
malformed query string. This could simply be a link to another Web page, or a link in an
HTML e-mail.
Once the victim clicks the link, the victim's browser makes a GET request to the
vulnerable server, bypassing the malicious query string.

The vulnerable server echoes the malicious query string back to the victim's browser, and
the browser executes the JavaScript embedded in the response.
Modes of PHP cross-site scripting
There are three modes of PHP cross-site scripting:



Reflected: An attacker provides a link or other payload containing embedded malicious
content, which the application immediately displays back to the victim. This is the
primary form of phishing via e-mail (such as eBay scams, bank scams, etc.).
Persistent: An attacker stores malicious content within a database, which is then exposed
to victims at a later time. This is the most common form of the cross-site scripting attack
against forum and Web mail software.
DOM: An attacker uses the victim site's JavaScript code to perform reflected cross-site
scripting. This technique is not widely used as yet, but it is just as devastating as any
form of cross-site scripting.
Web ripping
Web ripping is a technique in which the attacker copies the whole structure of a Web site to the
local disk and obtains all files of the Web site. Web ripping helps an attacker trace the loopholes
of the Web site.
Web services architecture
The following is the Web services architecture:
Web services attacks
Web services are typically application programming interfaces (API) or Web APIs that are
accessed via the Hypertext Transfer Protocol (HTTP) and executed on a remote system hosting
the requested services. An attacker can inject a malicious script into a Web service, which can
enable disclosure and modification of data. The following are countermeasures against Web
services attacks:



Turning off Web services that are not required
Providing multiple layers of protection
Blocking all known attack paths for Web services
Web services XML poisoning
Attackers perform XML node manipulation or XML schema poisoning by inserting malicious
XML codes in SOAP requests to produce errors in XML parsing logic and break execution logic.
Attackers can manipulate XML external entity references that can result in an arbitrary file or
TCP connection openings and can be exploited for other Web service attacks. XML poisoning
allows attackers to perform a Denial of Service attack and compromise confidential information.
Using Burp suite for Web spidering
The following actions should be taken for Web spidering using Burp suite:
1. Configure a Web browser in order to use Burp as a local proxy.
2. Visit every possible URL to access the entire target application and submit all the
application forms available.
3. Browse the target application with JavaScript enabled and disabled, and with cookies
enabled and disabled.
4. Check the site map that the Burp proxy generates and identify any hidden application
content or functions.
5. Repeat these steps recursively until no further content or functionality is recognized.
Web services parsing attacks
Web services parsing attacks create a Denial of Service attack or produce logical errors in Web
service request processing by exploiting vulnerabilities and weaknesses in the processing
capabilities of the XML parser. The following are payloads:


Recursive payloads: An attacker queries for Web services with a grammatically correct
SOAP document that includes infinite processing loops leading to exhaustion of XML
parser and CPU resources.
Oversize payloads: An attacker sends a payload that is excessively large to consume all
system resources. This renders Web services inaccessible to other legitimate users.
XML injection
Attackers manipulate XML schema or manipulate XML schema or populate XML database with
bogus entries by injecting XML data and tags into user input fields. XML injection can be used
for the following purposes:



To bypass authorization
To escalate privileges
To generate Web services DoS attacks
SOAP injection
An attacker bypasses Web services authentication mechanism and accesses backend databases
by injecting malicious query strings in the user input field. SOAP injection attacks work like
SQL injection attacks.
Web services probing attack
An attacker analyzes the WSDL document in order to determine the following after trapping it
from Web service traffic:



Purpose of the application
Functional break down
Entry points and message types
The attacker then selects a set of operations and formulates the request messages on the basis of
rules of the XML schema that can be submitted to the Web service to create a set of valid
requests. The attacker uses these requests in order to include malicious content in SOAP requests
and analyzes errors in order to deeply understand potential security weaknesses.
Web service attack tools
The following are Web service attack tools:


soapUI: It is a leading desktop application. It is used for inspecting, invoking,
monitoring, simulating/mocking and functional/load/compliance/surveillance testing of
REST/WADL and SOAP/WSDL-based Web services over HTTP. This tool is used to
perform Web services probing, SOAP injection, XML injection, and Web services
parsing attacks. Service simulation, functional testing, and load testing are features of the
soapUI tool.
Altova XMLspy: It is the XML editor. It is used for modeling, editing, transforming, and
debugging XML-related technologies. It provides unsurpassed compliance with the latest
industry standards for Web services development.
13.4 Identify Web application hacking and Web application security tools
Exam Focus: Identify Web application hacking and Web application security tools. Objective
includes:

Understand Web application hacking methodology.



Identify Web application hacking tools.
Understand how to defend against Web application attacks.
Identify Web application security tools.
Web App hacking methodologies
The following are Web App hacking methodologies:










Footprint Web infrastructure
Attack Web Servers
Analyze Web applications
Attack authentication mechanism
Attack authorization schemes
Attack session management mechanism
Perform injection attacks
Attack data connectivity
Attack Web App client
Attack Web services
Footprint Web infrastructure
Web infrastructure footprinting supports attackers in selecting victims and identifying vulnerable
Web applications.




Server discovery: It finds the physical servers that host a Web application.
Service discovery: It finds the services that run on Web servers. These services can be
exploited as attack paths for Web app hacking.
Server identification: It grabs server banners in order to identify the make and versions
of the Web server software.
Hidden content discovery: It extracts content and functionality that is not directly linked
or reachable from the main visible content.
Server discovery
Server discovery provides information regarding the location of servers and makes sure that the
target server is alive on Internet. The Whois lookup utility provides information regarding the IP
address of Web server and DNS names. The following are Whois lookup tools:




http://www.tamos.com
http://netcraft.com
http://www.whois.net
http://www.iptools.com
DNS interrogation delivers information regarding the location and type of servers. The following
are DNS interrogation tools:




http://www.dnsstuff.com
http://network-tools.com
http://www.checkdns.net
http://www.iptools.com
Port scanning tries to connect to a specific set of TCP or UDP ports in order to determine the
service that is present on the server. Nmap, NetScan Tools Pro, and Hping are port scanning
tools.
Service discovery
The target Web server is scanned in order to identify common ports that are used by Web servers
for different services. Nmap and NetScan Tools Pro are tools used for service discovery.
Identified services serve as attack paths for Web application hacking. The following ports are
used by HTTP services:
Ports
Typical HTTP services
80
World Wide Web standard port
81
Alternate WWW
88
Kerberos
443
SSL (https)
900
IBM Websphere administration client
2301 Compaq Insight Manager
2381 Compaq Insight Manager over SSL
4242 Microsoft Application Center Remote management
7001 BEA Weblogic
7002 BEA Weblogic over SSL
7070 Sun JAVA Web Server over SSL
8000 Alternate Web server or Web cache
8001 Alternate Web server or management
8005 Apache Tomcat
9090 Sun Java Web Server admin module
10000 Netscape Administrator interface
Server identification/ banner grabbling
The server response header field is analyzed in order to identify the make, model, and version of
the web server software. Attackers use this information for selecting the exploits from
vulnerability database so that they may attack a webserver and applications. Telnet, Netcat,
Fscan, and ID Serve are banner grabbling tools.
Hidden content discovery
The hidden content and functionality that cannot be reached from the main visible content is
discovered in order to exploit user privileges within the application. By this, an attacker can
recover the following:




Backup copies of live files
Configuration files and log files including sensitive data
Backup archives including snapshots of files within the web root
New functionality, which is not linked to the main application
Web spiders parse HTML form and client-side JavaScript requests and responses to
automatically discover the hidden content. Paros, Burp Spider, and WebScarab are Web
spidering tools.
An attacker accesses all of the application's functionality and monitors all requests and responses
by using an intercepting proxy. The intercepting proxy parses all the application's responses and
reports the content and functionality that it discovers. Poras Proxy is a tool used for attackerdirected spidering tool.
In brute forcing, an attacker guesses the names or identifiers of hidden content and functionality
by using automation tools such as Burp suite for making huge number of requests to the Web
server.
Analyze Web applications
The active application's functionality and technologies are analyzed to identify the attack
surfaces that it exposes. The following actions should be taken for analyzing Web applications:




Identify entry points for user: In order to identify the user input entry points, review the
generated HTTP request.
Identify server-side functionality: In order to identify the server-side structure and
functionality, observe the applications revealed to the client.
Identify server-side technologies: Use fingerprint techniques such as HTTP
fingerprinting to fingerprint the technologies active on the server.
Map the attack surface: Recognize the various attack surfaces that are uncovered by the
applications and the vulnerabilities that are related.
Identifying entry points for user input
URL, HTTP header, query string parameters, POST data, and cookies are examined to determine
all user input fields. HTTP header parameters that the application can process as user inputs such
as User-Agent, Referer, Accept, Accept-Language, and Host headers are identified. URL
encoding techniques are determined and other encryption measures are implemented in order to
secure the Web traffic such as SSL. Burp proxy, HttPrint, WebScarab, and Paros Proxy are tools
that are used to identify entry points for user input.
Identifying server-side technologies
The following actions should be taken in order to identify server side technologies:




A detailed server fingerprinting should be performed and HTTP headers and HTML
source code should be analyzed.
URLs for file extensions, directories, and other identification information should be
examined.
The error page messages should also be examined.
The following session tokens are examined:
o JSESSIONID: Java
o ASPSESSIONID: IIS server
o ASP.NET_SessionId: ASP.NET
o PHPSESSIS: PHP
Identify server-side functionality
Page source and URLs are examined and an educated guess is made in order to determine the
internal structure and functionality of Web applications. Tools such as Wget, Teleport Pro, and
BlackWidow are used to identify server-side functionality.
Attack authentication mechanism
Design and implementation flaws in Web applications can be exploited by attackers to bypass
authentication mechanisms. A failure to check password strength or insecure transportation of
credentials can exploit design and implementation flaws in Web applications.
Username enumeration
The trial-and-error method can be used to guess the users of the application if login error states
the part of the username and password that is incorrect. There are some applications that
automatically produce account usernames depending on a sequence such as username211,
username212, username213, etc. and attackers can find the sequence and enumerate valid
usernames.
Password attacks
Password changing: Spider the application or create a login account to determine password
change functionality within the application. In order to identify vulnerabilities in password
change functionality, try random strings for "Old Password", "New Password", and "Confirm the
New Password" fields and analyze errors.
Password recovery: For password recovery, an attacker can use social engineering to guess the
password if the number of attempts is not limited. Applications may also send a unique recovery
URL or existing password to email the address specified by the attacker.
"Remember Me" exploit: A simple persistent cookie, such as RememberUser=mark or a
persistent session identifier, such as RememberUser=ABY15982010 can be used to implement
"Remember Me" functions. Attackers can bypass the authentication mechanism by using an
enumerated username or predicting the session identifier.
In password guessing, attackers use most commonly used passwords, footprinting target, and
social engineering techniques to create a list of possible passwords, and try each password until
the correct password is found. Attackers can use tools such as Dictionary Maker to create
dictionary of all possible passwords. This helps them to perform dictionary attacks. Password
guessing can be carried out manually or using automated tools such as WebCracker, Brutus,
Burp Insider, and THC-Hydra, etc.
In brute forcing, attackers try all possible values from a set of alphabets, numeric, and special
characters to crack the log-in passwords. Attackers can use the following password cracking
tools:



Burp Suite's Intruder
Brutus
Sensepost's Crowbar
Cookie exploitation
Attackers can use techniques such as script injection and eavesdropping to steal the cookie if the
cookie includes passwords and session identifiers. Attackers then replay the cookie with the
same or altered passwords or session identifiers in order to bypass Web application
authentication. Attackers can use tools such as Paros Proxy, Burp Suite, etc. to trap cookies.
Authorization attack
Attackers modify input fields that relate to user ID, username, access group, cost, filenames, file
identifiers, etc. to manipulate the HTTP requests so that they may subvert the application
authorization schemes. Attackers first access a Web application using a low privileged account,
and then access protected resources by escalating privileges.
Cookie parameter tampering
An attacker gathers some cookies that are set by the Web application and analyzes them to find
the cookie generation mechanism. The attacker then traps cookies that are set by Web
application, tampers with its parameters using tools such as Paros Proxy, and replay to the
application.
Session management attack
Attackers break an application's session management mechanism for the following purposes:


To bypass the authentication controls
To impersonate privileged application users
Session tokens prediction and session tokens tampering are used for session token generation.
Session hijacking, session replay, and man-in-the middle attacks are used for session token
handling.
Injection attacks
In injection attacks, attackers provide crafted malicious input that is syntactically correct
according to the interpreted language. The interpreted language is used to break application's
normal intend. The following are the types of injection attacks:






Web script injection: In Web script injection, a crafted input that breaks the intended
data context and executes commands on the server is entered if user input is used into
code that is dynamically executed.
SQL injection: In SQL injection, a series of malicious SQL queries is entered into input
fields in order to directly manipulate the database.
LDAP injection: In LDAP injection, an advantage of non-validated Web application
input vulnerabilities is taken to pass LDAP filters to directly access databases.
XPath injection: In XPath injection, malicious strings are entered in input fields to
manipulate the XPath query so that it interferes with the application's logic.
SMTP injection: In SMTP injection, to generate large volumes of spam email, inject
arbitrary SMTP commands into application and SMTP server conversation.
OS commands injection: In OS commands injection, malicious codes are entered in
input fields to exploit operating systems if applications use user input in a system-level
command.
Attack data connectivity
Database connection strings are used for connecting applications to database engines. Instead of
abusing database queries, the way applications are connected to the database is exploited by
database connectivity attacks. Connection string injection, connection string parameter pollution
(CSPP) attacks, and connection pool DoS are data connectivity attacks.
In connection string injection, the attacker injects parameters in a connection string by appending
them with the semicolon (;) character in a delegated authentication environment. A connection
string injection attack takes place when connection strings are built based on user input by using
a dynamic string concatenation.
CSPP attacks involve overwriting parameter values in the connection string. In hash stealing, the
value of Data Source Parameter is replaced with that of a Rogue Microsoft SQL Server
connected to the Internet running a sniffer.
In port scanning, an attacker changes the value and sees the error messages obtained to connect
to different ports. In hijacking Web credentials, an attacker uses the Web Application System
account instead of a user-provided set of credentials to connect to the database.
In connection pool DoS, an attacker takes the following steps in order to consume all
connections in the connection pool:
1. Examine the connection pooling settings of the application.
2. Construct a large malicious SQL query
3. Run multiple queries simultaneously
This causes database queries to fail for legitimate users.
Attack Web services
Web services work on the top of the legacy Web applications. An underlying application's
business and logic vulnerabilities will be exposed for various attacks when there is an attack on a
Web service.
Web application hacking tools
The following are Web application hacking tools:






Instant Source: It allows a user to see and edit the HTML code of the Web page at
runtime.
Wget: Wget is a computer program that retrieves contents from Web servers. It is a part
of the GNU project. It currently supports downloading via the HTTP, HTTPS, and FTP
protocols, the most popular TCP/IP-based protocols used for Web browsing. Its features
include recursive download, conversion of links for offline viewing of local HTML,
support for proxies, and much more.
WebSleuth: WebSleuth is a manual research and exploration tool for Web applications.
It can be used to get an efficient listing of all links, forms, script, and frames, to edit form
elements and links, and to execute JavaScript commands with the document.
BlackWidow: BlackWidow is a Website scanner, a site mapping tool, a site ripper, and a
site mirroring tool. It also works as an offline browsing program.
BURP: Burp Proxy is a proxy server for security testing of Web applications, which
operates as a man-in-the-middle between the browser and the target application.
cURL: cURL is a command-line tool for transferring data with URL syntax, supporting
DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS,
POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, TELNET, and TFTP.
CookieDigger
CookieDigger is used to identify weak cookie generation and insecure implementations of
session management by Web applications. It collects and analyzes cookies that a Web
application issues for multiple users. It reports on the following:


Predictability and entropy of the cookie
Whether critical information such as, user name and password, are included in the cookie
values
Hacking webservers
The server for known vulnerabilities should be scanned by using any webserver vulnerability
scanner after identifying the webserver environment. In order to exploit identified vulnerabilities,
launch a webserver attack. The following tools are used for hacking webservers:


UrlScan
Nikto




Nessus
WWWhack
Acunetix Web Vulnerability Scanner
WebInspect
Web application security tools
The Web application security tools are as follows:







Nikto: Nikto is an open-source Web server scanner that tests Web servers for dangerous
files/CGIs, outdated server software, and other problems. It performs generic and servertype specific checks. It also captures and prints any cookies received. It can work in both
Linux and Windows environments. Nikto performs comprehensive tests against Web
servers for multiple items, including over 6100 potentially dangerous files/CGIs.
Paros proxy: Paros is a Web application vulnerability scanner that supports
editing/viewing HTTP/HTTPS messages on-the-fly to change items such as cookies and
form fields. It also includes various features, such as Web traffic recorder, Web spider,
hash calculator, and a scanner for testing common Web application attacks such as SQL
injection and cross-site scripting.
WebScarab: WebScrab is a framework for analyzing the applications that communicate
using the HTTP and HTTPS protocols.
WebInspect: WebInspect is a Web application vulnerability scanner that is used to
perform various Web attacks such as parameter injection, cross-site scripting, directory
traversal, etc.
Whisker/libwhisker: Whisker is an HTTP/Web vulnerability scanner that is written in
the PERL language. Whisker runs on both Windows and UNIX environments. It provides
functions for testing HTTP servers for many known security holes, particularly the
presence of dangerous CGIs.
Wikto: Wikto works in the same manner as Nikto, but it also adds various
functionalities, such as a Back-End miner and close Google integration.
N-Stealth: N-Stealth is a commercial Web server security scanner which includes tools
such as Nessus, ISS Internet Scanner, Retina, SAINT, and Sara.
Acunetix Web Vulnerability Scanner
Acunetix Web Vulnerability Scanner uses a crawler to detect Web server type and application
language. It includes advanced penetration testing tools, such as the HTTP Editor and the HTTP
Fuzzer. Port scans a Web server and runs security checks against network services. Web forms
and password protected areas are tested.
Acunetix Web Vulnerability Scanner has an automatic client script analyzer. The automatic
client script analyzer permits security testing of Ajax and Web 2.0 application. An administrator
uses the automatic client script analyzer to perform in-depth SQL injection and cross-site
scripting testing.
Falcove Web vulnerability scanner
Falcove is used to scan Website for application layer vulnerabilities. A user uses Falcove to
penetrate into the system via vulnerable Web applications and misconfigured database
connections. It detects the Web vulnerabilities, such as cross-site scripting, SQL injection, code
execution attacks, and input validation, by crawling the Website.
Netsparker
Netsparker is used to perform automated comprehensive Web application scanning for
vulnerabilities. SQL injection, cross-site scripting, and remote code injections may be the
vulnerabilities. It detects, confirms, and exploits vulnerabilities in a single integrated
environment.
N-Stalker Web application security scanner
N-Stalker Web application security scanner is an effective suite of Web security assessment
checks. It is used to enhance the overall security of Web applications against a wide range of
vulnerabilities and sophisticated hacker attacks. It includes all Web security assessment checks,
such as code injection, cross-site scripting, parameter tampering, and Web server vulnerabilities.
dotDefender
dotDefender is a software based Web application firewall, which complements the network
firewall, IPS, and other network-based Internet security products. For suspicious behavior,
dotDefender inspects the HTTP/HTTPS traffic. dotDefender is used to detect and block injection
attacks.
IBM Relational AppScan
IBM Relational AppScan is a Web application security testing tool. It is used to automate
vulnerability assessments. It prevents SQL injection attacks on Websites, and scans Web sites for
embedded malware.
ServerDefender VP
ServerDefender VP blocks threats, such as cross-site scripting, SQL injection, buffer overflows,
file injection, Denial of Service, cookie poisoning, and schema poisoning, to secure the sensitive
data content.
Encoding schemes
Web applications use different encoding schemes to safely handle unusual characters and binary
data in the desired way. The following are the types of encoding schemes:


URL encoding: It is used to convert URL into a valid ASCII format to safely transport
the data over HTTP. It replaces unusual ASCII characters with "%" followed by the
character's two digit ASCII code expressed in hexadecimal.
HTML encoding: It represents unusual characters so that they can be safely combined
within an HTML document. It defines several HTML entities in order to represent
particularly usual characters.
Encoding schemes
The following are encoding schemes:



Unicode encoding: 16-bit Unicode encoding replaces unusual Unicode characters with
"%u" followed by the character's Unicode code point expressed in hexadecimal. UTF-8 is
a variable length encoding standard. It uses each byte expressed in hexadecimal and
preceded by the % prefix.
Base64 encoding: It uses only printable ASCII characters to represent any binary data. It
is generally used to encode email attachments for safe transmission over SMTP. It is also
used to encode user credentials.
Hex encoding: It represents a collection of characters for transmitting binary data by
using hex value of every character.
Defending against Web application attacks
The following actions should be taken against Web application attacks:















Input validation should be performed.
WAF firewall/ IDS and filter packets should be used.
The firewall should be configured to deny external ICMP traffic access.
The unnecessary service and ports should be shut down.
Patches should be kept current.
User input should be sanitized and filtered.
The source code for SQL injection should be analyzed.
The use of 3rd party apps should be minimized.
Dynamic testing and source code analysis should be performed.
LDAP filter should be made as specific as possible.
Verbose error messages should be disabled and custom error pages should be used.
Non-privileged account should be used to connect to the database.
Stored procedures and parameter queries should be used.
Least privileges should be granted to the database, tables, and columns.
Commands such as xp_cmdshell should be disabled.
Defending against a SQL injection attack
The following actions should be taken against a SQL injection attack:










The length of user input should be limited.
Custom error messages should be used.
DB traffic should be monitored using an IDS and WAP.
Commands such as xp_cmdshell should be disabled.
The database server and Web server should be disabled.
The attribute set to the POST method should always be used.
The database service account with minimal rights should be run.
The database server and Web server should be isolated.
Extended stored procedures should be moved to an isolated server.
Low privileged account should be used for DB connection.
Defending against command injection flaws
The following actions should be taken to defend against command injection flaws:








Input validation should be performed.
Dangerous characters should be escaped.
Language-specific libraries that avoid problems due to shell commands should be used.
Input and output encoding is performed.
A safe API that avoids using interpreter entirely should be used.
Parameterized SQL queries should be used.
Requests should be structured so that all supplied parameters are treated as data, rather
than potentially executable content.
Modular shell disassociation from kernel should be used.
Defending against a DoS attack
The following actions should be taken to defend against a DoS attack:






The firewall should be configured in order to deny external Internet Control Message
Protocol traffic access.
The remote administration and connectivity testing should be secured.
Use of unnecessary functions such as gets, strcpy should be prevented.
The sensitive information should not be overwritten.
Thorough input validation should be performed.
Data that is processed by the attacker should be stopped from being executed.
Defending against a Web services attack
The following actions should be taken to defend against a Web services attack:









In order to grant or deny access to any type of WSDL based SOAP messages, configure
WSDL Access Control Permissions.
Document-centric authentication credentials that use SAML should be used.
Multiple security credentials such as X.509 Cert, SAML assertions and WS-Security
should be used.
Web services-capable firewalls that can perform SOAP and ISAPI level filtering should
be deployed.
Firewalls/IDS systems for a Web services anomaly and signature should be configured.
Firewall/IDS systems should be configured to filter improper SOAP and XML syntax.
Centralized in-line requests and responses schema validation should be implemented.
External references should be blocked and pre-fetched content should be used when dereferencing URLs.
A secure repository of XML schemas should be maintained and updated.
Defending against XSS attacks
The following actions should be taken to defend against XSS attacks:








All headers, cookies, query strings, form fields, and hidden fields should be validated
against a rigorous specification.
XSS vulnerabilities can be defeated by filtering script output. This prevents them from
being transmitted to users.
Input and output should be encoded and Meta characters in the input should be filtered.
A Web application firewall should be used to block the execution of malicious script.
Websites that use HTTPS when it comes to XSS should not always be trusted.
All non-alphanumeric characters should be converted to HTML character entities before
displaying the user input in search engines and forums.
Testing tools should be used extensively during the design phase. They are required to
remove such XSS holes in the application before it goes into use.
Some standard or signing scripts should be developed with private and public keys that
actually check in order to ascertain whether the script introduced is really authenticated.
13.5 Understand Web application firewalls, and gain insights on Web application pen testing
Exam Focus: Understand Web application firewalls, and gain insights on Web application pen
testing. Objective includes:


Understand Web application firewalls.
Gain insights on Web application pen testing.
Web application firewall
A Web application firewall is a type of firewall that controls input, output, and/or access from,
to, or by an application or service. It monitors and blocks the input, output, or system service
calls that do not meet the configured policy of the firewall. A Web application firewall controls
all network traffic on any OSI layer up to the application layer. Popular Web application
firewalls:













NAXSI Firewall
Armorlogic Firewall
Array Networks Web Application Firewall
Barracuda Web Application Firewall
Cisco Application Control Engine (ACE) Web Application Firewall
Citrix NetScaler
F5 Networks Application Security Manager ASM
Fortinet Web application Firewall
ModSecurity Web application Firewall
MONITORAPP WEB INSIGHT SG Application Firewall
Radware Web Application Firewall
SonicWALL Web Application Firewall Service
Imperva Web Application Firewall
Web application pen testing
Web application pen testing is used to identify, analyze, and report vulnerabilities in a given
application. The vulnerabilities may be input validation, buffer overflow, SQL injection,
bypassing authentication, and code execution. Conducting a series of methodical and repeatable
tests and going through all the different application vulnerabilities is the best way to perform
penetration testing.
Web application pen testing is required due to the following reasons:



Identification of ports: The ports are scanned in order to identify the associated running
services and perform automated or manual tests to analyze the services and find
weaknesses.
Verification of vulnerabilities: The issue is tested and fixed to exploit the vulnerability.
Remediation of vulnerabilities: The solution is retested against vulnerability to ensure
that it is completely secure.
ACL
Access control list (ACL) is a rule list containing access control entries. It is used to allow or
deny access to network resources. ACL can be implemented on network users and network
devices such as routers and firewalls. Routers and firewalls use ACL to determine which packets
should be forwarded or dropped.
Steps in Web application testing
In Web application penetration testing, a Penetration Tester needs to take the following steps:
1. Information gathering testing
o Analyzing the robots.txt file
o Performing search engine reconnaissance
o Identifying application entry points
o Identifying Web applications
o Analyzing the output from head and options http requests
o Implementing techniques such as DNS zone transfers, DNS inverse queries, Webbased DNS searches, and querying search engines
o Analyzing error codes
o Testing for recognized file types/extensions/directories
o Examining source of available pages
o TCP/ICMP and service fingerprint
2. Authentication testing
o Testing for vulnerable remember pw and pw reset
o Testing for logout and browser cache management
o Testing for captcha
o Testing for multiple factors authentication
o Testing for race conditions
3. Session management testing
o
4.
5.
6.
7.
8.
Testing for session management using cookie tampering that results in hijacking
the sessions of legitimate users
o Testing for cookie attributes to hijack sessions using tools such as Webscarab,
Burp, Paros, and Tamper
o Testing for session fixation using tools like Webscarab
o Testing for exposing session variables to get the confidential information
o Testing for CSRF to compromise end user data and operate the entire Web
application
Authorization testing
o Testing for path traversal
o Testing for bypassing authorization schema
o Testing for privilege escalation
Data validation testing
o Testing for reflected XSS
o Testing for stored XSS
o Testing for DOM-based XSS
o Testing for cross-site flashing
o Performing SQL Injection
o Performing LDAP injection using Softerra and LDAP Browser tools
o Performing ORM injection using Hibernate, NHibernate, and Ruby On Rails
o Performing XML injection by inserting XML metacharacters
o Performing XPath injection by changing the query result
o Performing IMAP/SMTP injection by trying to access the backend mail server
o Performing code injection attacks
o Performing OS commanding attacks
o Performing buffer overflow attacks by OllyDbg
o Testing for HTTP splitting/smuggling
DoS attack penetration testing
o Performing SQL wild character attacks
o Locking customer accounts to check login account info
o Performing Buffer overflow attacks
o Writing user provided data to disk to check local disk capacity
o Checking for programming flaws
o Storing too much data in a session to check the session management errors
Performing Web services testing
o Gathering Web services information such as UDDI, WSDL, SOAP, and UBR
o Searching WSDL entry points using WSDigger, WebScarab, and Foundstone
o Testing XML structural issues using XML parser such as WSDigger
o Testing issues in HTTP GET parameters
o Testing SOAP attachments using Wireshark and WebScarab
Testing AJAX applications
o Testing AJAX application call endpoints using Sprajax
o Parsing the HTML and JavaScript files
o Using a proxy to observe traffic
Web application countermeasures
The following are Web application countermeasures:

































Redirects and forwards should be avoided.
It should be ensured that the supplied value is valid and authorized for the user if
destination parameters cannot be avoided.
SSL should be used for authenticated parts of the application.
It should be verified whether all the users' identities and credentials are stored in a hashed
form.
Session data should not be submitted as part of a GET and POST.
A user should be logged of immediately and clear the history after using a Web
application.
A user should not allow browser and Websites to save login details.
The HTTP Referrer header should be checked, and URL parameters should be ignored
when a POST is processed.
Weak cryptographic algorithms should not be created or used.
Encryption keys should be generated offline and stored securely.
It should be ensured that encrypted data stored on disk cannot be easily decrypted.
Non-SSL request to Web pages should be redirected to the SSL page.
The "secure" flag should be set on all sensitive cookies.
SSL provider should be configured to support only strong algorithms.
It should be ensured that the certificate is valid, not expired, and matches all domains that
are used by the site.
SSL and other encryption technologies should be used by backend and other connections.
Access rights to the protected areas of the Website should be defined.
Checks/hotfixes that prevent the exploitation of the vulnerability such as Unicode to
affect the directory traversal should be applied.
Web servers should be updated with security patches in a timely manner.
Plain text or weakly encrypted passwords should not be stored in a cookie.
Cookie's timeout should be implemented.
Cookie's authentication credentials should be associated with an IP address.
Logout functions should be made available.
All security mechanisms should be configured and all unused services should be turned
off
Roles, permissions, and accounts should be setup and all default accounts should be
disabled or their default passwords should be changed.
Latest security vulnerabilities should be scanned and latest security patches should be
applied.
Type, pattern, and domain value validation should be performed on all input data.
LDAP filter should be made as specific as possible.
The amount of data returned to the users should be validated and restricted.
Tight access control should be implemented on the data in the LDAP directory.
Dynamic testing and source code analysis should be performed.
User input should be strongly validated.
Implementing a chroot jail should be considered.
Chapter Summary
In this chapter, we learned about Web applications, Web application components, and working
of Web applications. In this chapter, we discussed about Web application hacking, Web
application security tools, and Web App hacking methodologies. This chapter also focused on
Web application firewalls and Web application pen testing.
Glossary
Acunetix Web Vulnerability Scanner
Acunetix Web Vulnerability Scanner uses crawler to detect Web server type and application
language.
CookieDigger
CookieDigger is used to identify weak cookie generation and insecure implementations of
session management by Web applications.
Cross-site scripting attack
A cross-site scripting attack is one in which an attacker enters malicious data into a Website.
Falcove
Falcove is used to scan Websites for application layer vulnerabilities.
Injection flaws
Injection flaws are the vulnerabilities where a foreign agent illegally uses a sub-system. They are
the vulnerability holes that can be used to attack a database of Web applications. It is the most
common technique of attacking a database.
SQL injection attacks
SQL injection attacks use a series of malicious SQL queries in order to directly manipulate the
database.
Web services parsing attacks
Web services parsing attacks exploit vulnerabilities and weaknesses in the processing
capabilities of the XML parser in order to create a Denial of Service attack or produce logical
errors in Web service request processing.
XRX
In software development, XRX is a Web application architecture based on XForms, REST, and
XQuery. XRX applications store data on both the Web client and on the Web server in the XML
format and do not require a translation between data formats. XRX is considered as a simple and
elegant application architecture due to the minimal number of translations needed to transport
data between client and server systems.
Download