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

Unit 3 SQL Injection

Uploaded by

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

Unit 3 SQL Injection

Uploaded by

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

UNIT III SQL INJECTION 9

Attacking SQL Servers - Sniffing - Brute Forcing and Finding Application Configuration
Files - Input Validation Attacks - Preventive Measures - Web Application Threats - Web
Application Hacking - Cross Site Scripting / XSS Flaws / Countermeasures Correct Web
Application Set-up.

3.1 Attacking SQL Servers


Attacking SQL servers involves targeting and exploiting vulnerabilities in the SQL server
software itself. This can be done through various techniques and methods to gain
unauthorized access to the server, execute commands on the operating system, or access other
parts of the server's file system.

One common method used in attacking SQL servers is SQL Injection. SQL Injection attacks
occur when an attacker manipulates the input fields of a web application to inject malicious
SQL code into the application's database query. By exploiting improper validation or
escaping of user inputs in SQL statements, the attacker can execute unauthorized SQL
commands and potentially gain access to sensitive data, modify data, or compromise the
server.

To understand SQL Injection attacks, let's consider an example. Imagine a web application
that takes user input, such as a username or search query, and uses that input to construct an
SQL query to retrieve data from the database. If the application does not properly validate or
sanitize the user input, an attacker can manipulate the input to inject their own SQL code.

For instance, if the input is not properly sanitized and the attacker enters something like ' OR
1=1 the resulting SQL query may become:

SELECT * FROM users WHERE username='' OR 1=1 --' AND


password='somepassword'

In this example, the injected code ' OR 1=1 -- causes the SQL query to always return true
(1=1 is a true condition), effectively bypassing any authentication mechanism in place. The --
is used to comment out the rest of the original query, preventing any errors.
By exploiting SQL Injection vulnerabilities, attackers can gain unauthorized access to
sensitive data, such as usernames, passwords, or financial information stored in the database.
They can also modify or delete data, inject malicious code into the database, or even execute
operating system commands if the database server has certain privileges.

While SQL Injection attacks are a common method used to attack SQL servers, it's important
to note that there are also other methods that can be employed. These methods involve
exploiting vulnerabilities in the SQL server software itself, rather than targeting the web
application layer.
For example, attackers may exploit known vulnerabilities in the SQL server software to gain
unauthorized access or execute arbitrary commands on the server. These vulnerabilities can
include flaws in authentication mechanisms, privilege escalation vulnerabilities, buffer
overflows, or insecure configurations.
By exploiting these vulnerabilities, attackers can bypass security measures, gain
administrative rights, and carry out more malicious actions or gain unauthorized access to
specific areas of the system. The impact of a successful attack on an SQL server can be
severe, including data theft, data manipulation, service disruptions, and compromised user
confidence.

SQL Injection Types


There are different types of SQL injection attacks:
1. In-band SQL Injection
It involves sending malicious SQL queries directly through the web application’s interface
and allows attackers to extract sensitive information or modify the database itself.
2. Error-based SQL Injection
Attackers exploit error messages generated by the web application by analyzing error
messages to gain access to confidential data or modify the database.
3. Blind SQL Injection
Attackers send malicious SQL queries and observe the application’s response. By analyzing
the application’s behavior, attackers can determine the success of the query.
4. Out-of-band SQL Injection
Uses a different channel to communicate with the database. Allows attackers to exfiltrate
sensitive data from the database.
5. Inference-based SQL Injection
Uses statistical inference to gain access to confidential data. Attackers create queries that
return the same result regardless of input values.
Impact of SQL Injection
The hacker can retrieve all the user data present in the database such as user details, credit
card information, and social security numbers, and can also gain access to protected areas like
the administrator portal. It is also possible to delete user data from the tables.
Nowadays, all online shopping applications and bank transactions use back-end database
servers. So in case the hacker is able to exploit SQL injection, the entire server is
compromised.
To prevent and mitigate attacks on SQL servers, it is crucial to implement proper security
measures. Some recommended practices include:
1. Regular Patching and Updates: Keep the SQL server software up to date with the
latest security patches and updates. This helps protect against known vulnerabilities
that attackers may exploit.
2. Secure Configuration: Ensure that the SQL server is properly configured with secure
settings, such as strong authentication mechanisms, limited privileges for database
accounts, and secure network configurations.
3. Access Control: Implement strict access control measures to limit access to the SQL
server and its resources. Use strong passwords, enforce least privilege principles, and
regularly review and revoke unnecessary privileges.
4. Monitoring and Logging: Implement robust monitoring and logging mechanisms to
detect and track any suspicious activities or unauthorized access attempts. Regularly
review logs for signs of potential attacks.
5. Security Testing: Conduct regular security testing, including vulnerability
assessments and penetration testing, to identify and address any weaknesses or
vulnerabilities in the SQL server.
By following these best practices and staying vigilant, organizations can significantly reduce
the risk of successful attacks on their SQL servers.
3.2 Sniffing
Sniffing in SQL Server, specifically parameter sniffing, occurs when the SQL Server
optimizer generates an execution plan for a stored procedure based on the parameters passed
during the first execution. This can lead to both positive and negative effects on query
performance.
The following causes and factors related to parameter sniffing in SQL Server can be
identified:
1. Different Parameter Values: When different parameter values are passed to a stored
procedure, SQL Server may generate different execution plans based on the specific
parameter values. This can result in suboptimal plans for certain parameter values,
leading to performance issues.
2. Data Distribution: Uneven data distribution in tables can contribute to parameter
sniffing issues. If the data distribution is skewed or uneven, the execution plan
generated for one set of parameter values may not be optimal for other sets of
parameter values.
3. Caching of Execution Plans: SQL Server caches execution plans for stored
procedures to improve performance. However, if the cached plan is not optimal for
certain parameter values, it can lead to parameter sniffing issues.
4. Query Optimization Process: The SQL Server optimizer tries to determine the best
execution plan for a query based on the available statistics and indexes. However, the
optimizer's estimation may not always accurately reflect the actual data distribution,
leading to suboptimal plans.
5. Recompilation: Recompiling a stored procedure can be a solution to address
parameter sniffing issues. By recompiling the procedure, SQL Server generates a new
execution plan based on the current parameter values. However, recompilation can
have its own overhead and may not always be the best solution.
It's important to note that parameter sniffing is not always a problem and can often result in
improved query performance. However, in certain scenarios, it can lead to suboptimal plans
and performance issues.

3.3 Brute Forcing and Finding Application Configuration Files


A brute force attack includes ‘speculating’ username and passwords to increase unapproved
access to a framework. Brute force is a straightforward attack strategy and has a high
achievement rate.
A few attackers use applications and contents as brute force devices. These instruments
evaluate various secret word mixes to sidestep confirmation forms. In different cases,
attackers attempt to get to web applications via scanning for the correct session ID. Attacker
inspiration may incorporate taking data, contaminating destinations with malware, or
disturbing help.
While a few attackers still perform brute force attacks physically, today practically all brute
force attacks are performed by bots. Attackers have arrangements of usually utilized
accreditations, or genuine client qualifications, got through security breaks or the dull web.
Bots deliberately attack sites and attempt these arrangements of accreditations, and advise the
attacker when they obtain entrance.
Types of Brute Force Attacks:
1. Dictionary attacks – surmises usernames or passwords utilizing a dictionary of
potential strings or phrases.
2. Rainbow table attacks – a rainbow table is a precomputed table for turning
around cryptographic hash capacities. It very well may be utilized to figure a
capacity up to a specific length comprising of a constrained arrangement of
characters.
3. Reverse brute force attack – utilizes a typical password or assortment of
passwords against numerous conceivable usernames. Focuses on a network of
clients for which the attackers have recently acquired information.
4. Hybrid brute force attacks – begins from outer rationale to figure out which
password variety might be destined to succeed, and afterward proceeds with the
simple way to deal with attempting numerous potential varieties.
5. Simple brute force attack – utilizes an efficient way to deal with ‘surmise’ that
doesn’t depend on outside rationale.
6. Credential stuffing – utilizes beforehand known password-username sets,
attempting them against numerous sites. Adventures the way that numerous
clients have the equivalent username and password across various frameworks.

How to Prevent Brute Force Password Hacking ?


To protect your organization from brute force password hacking, enforce the use of strong
passwords.
Passwords should:
 Never use information that can be found online (like names of family members).
 Have as many characters as possible.
 Combine letters, numbers, and symbols.
 Avoid common patterns.
 Be different for each user account.
 Change your password periodically
 Use strong and long password
 Use multifactor authentication

Find Application Configuration Files


Steps an Attacker Might Take to Find Application Configuration Files Using a Brute Force
Attack
1. Identify the target application: The attacker selects the application they want to
target and gathers information about it, such as the technology stack used, common
file naming conventions, and potential locations where configuration files might be
stored 1.
2. Generate a list of potential file names or paths: The attacker creates a list of
possible file names or paths that could lead to the application's configuration files.
This list can be based on common naming conventions, known default locations, or
any other information gathered about the application.
3. Automate the attack: The attacker uses automated tools or scripts to systematically
test each file name or path from the generated list. The tools send requests to the
application, attempting to access each file or path and analyzing the response
4. Analyze the responses: The attacker analyzes the responses received from the
application to determine if any of the tested file names or paths correspond to valid
configuration files. They may look for specific error messages, different HTTP
response codes, or any other indicators that suggest a successful access to a
configuration file.
5. Refine the attack: Based on the analysis of the responses, the attacker may refine
their list of potential file names or paths and repeat the process to increase the chances
of finding the configuration files

It's important to note that brute force attacks are illegal in most cases, unless an organization
has explicit consent to perform a penetration test on their own application. Engaging in any
form of unauthorized access or hacking is against the law and unethical.

If you suspect that your application's configuration files are vulnerable to unauthorized
access, it is recommended to take proactive measures to secure them. This can include
implementing strong access controls, using secure file permissions, and regularly updating
and patching your application to address any known vulnerabilities.

If you have concerns about the security of your application's configuration files, it is
advisable to consult with a cybersecurity professional or an expert in application security to
assess and address any potential vulnerabilities. Remember, it is important to always
prioritize ethical and legal practices when it comes to cybersecurity and protecting sensitive
information.
3.4 Input Validation Attacks
Input validation is the process of analyzing inputs and disallowing those which are
considered unsuitable. The idea behind input validation is that by only allowing inputs that
meet specific criteria, it becomes impossible for an attacker to enter an input designed to
cause harm to a system. Input validation should be used on any website or application that
allows user inputs. Even if a website or app doesn't store any confidential information,
allowing invalid inputs can also cause user experience issues.
Why Is Input Validation Important?
Input validation is important for two reasons, namely user experience and security.

 User Experience Users often enter invalid inputs, not because they are trying to
attack a website or app, but because they made a mistake. A user might spell a word
incorrectly, or provide the wrong information, such as entering their username in the
wrong box or trying an outdated password. When this happens, input validation can
be used to inform the user of their error, allowing them to rectify it quickly. Input
validation also prevents scenarios where sign-ups and sales are lost because a user is
not informed and so believes that correct input has been provided when it has not.
 Security Input validation prevents a wide range of attacks that can be performed
against a website or application. These cyberattacks can cause the theft of personal
information, allow unauthorized access to other components, and/or prevent a
website/application from functioning. The omission of input validation is also easy to
detect. Attackers can use automated programs to enter invalid inputs on websites in
bulk and determine how the websites react. They can then launch manual attacks on
any websites that aren't protected.
This means that a lack of input validation is not only an important vulnerability; it's a
vulnerability that will often be found and so can often cause hacks.
What Are Input Validation Attacks?
An input validation attack is any attack that involves adding malicious input into a user input
field. There are many different types of input validation attacks that attempt to do different
things.

1. Buffer Overflow A buffer overflow occurs when too much information is added to a
system. If input validation is not used, there's nothing stopping an attacker from
adding as much information as they want. This is called a buffer overflow attack. It
can cause a system to stop functioning and/or delete information that is currently
stored.
2. SQL Injection SQL injection is the process of adding SQL queries to input fields. It
might take the form of adding an SQL query to a web form or appending an SQL
query to a URL. The goal is to trick the system into executing the query. SQL
injection can be used to access secure data and to modify or delete data. This means
that input validation is particularly vital for any website or app which stores important
information.
3. Cross-Site Scripting Cross-site scripting involves adding code to user input fields. It
is often carried out by adding code onto the end of a URL belonging to a reputable
website. The URL can be shared through forums or social media and the code is then
executed when a victim clicks on it. This creates a malicious web page that appears to
be hosted on the reputable website.
The idea is that if a victim trusts the target website, they should also trust a malicious web
page that appears to belong to it. The malicious web page can be designed to steal keystrokes,
redirect to other pages, and/or begin automatic downloads.
How to Implement Input Validation
Input validation is not difficult to implement. You simply need to figure out what rules are
required to prevent invalid input and then add them to the system.

 Write All Data Inputs Create a list of all possible user inputs. This will require you
to look at all user forms and consider other types of input such as URL parameters.
 Create Rules Once you have a list of all data inputs, you should create rules that
dictate what inputs are acceptable. Here are a few common rules to implement.
 Whitelisting: Only allow specific characters to be input.
 Blacklisting: Prevent specific characters from being input.
 Format: Only allow inputs which adhere to a particular format, i.e. only allow email
addresses.
 Length: Only allow inputs of up to a certain length.
 Implement Rules In order to implement the rules, you will have to add code to the
website or application that rejects any input that doesn't follow them. Due to the threat
posed by invalid inputs, the system should be tested prior to going live.
 Create Responses Assuming that you want input validation to also help users, you
should add messages that explain both why an input is incorrect and what should be added
instead.

Input Validation Is a Requirement for Most Systems


Input validation is an important requirement for any website or app that allows user input.
Without controls over what input is added to a system, an attacker has a range of techniques
that can be used for hacking purposes. These techniques can crash a system, alter it, and/or
allow private information to be accessed. Systems without input validation become popular
targets for hackers and the internet is constantly being searched for them. While input
validation is primarily used for security purposes, it also plays an important role in telling
users when they add something incorrectly.
3.5 Preventive Measures for Input Validation Attacks
Input validation is a crucial security measure to prevent various types of attacks, such as SQL
injection, command injection, and cross-site scripting (XSS). By implementing proper input
validation techniques, you can significantly reduce the risk of input validation attacks. Here
are some preventive measures:

1. Thoroughly Validate and Sanitize Input: Implement robust input validation


mechanisms to ensure that user input meets the expected criteria, such as type, length,
format, and range. This helps prevent invalid or malicious data from entering the
system
2. Use Whitelisting: Implement allowlist input validation, where only known and
trusted inputs are accepted, rather than denylist validation, which tries to block
specific malicious inputs. Allowlisting is a more secure approach as it explicitly
defines acceptable inputs, reducing the risk of bypassing validation
3. Avoid Dynamic Code Execution: Avoid executing user input as code or system
commands directly. Instead, use parameterized queries or prepared statements to
separate user input from the code execution, preventing command injection and SQL
injection attacks.
4. Implement Content Security Policies (CSP): CSP is a security mechanism that
helps prevent cross-site scripting (XSS) attacks by defining and enforcing the allowed
sources of content, such as scripts, stylesheets, and images, on a web page
5. Regular Security Audits and Testing: Conduct regular security audits, penetration
testing, code reviews, and vulnerability assessments to identify and address potential
input validation vulnerabilities. This proactive approach helps detect weaknesses and
mitigate risks before they can be exploited 3.
6. Keep Software and Libraries Updated: Regularly update your software,
frameworks, and libraries to ensure that you have the latest security patches and fixes.
Outdated software may contain known vulnerabilities that attackers can exploit.
7. Educate Developers and Users: Provide training and awareness programs for
developers and users to understand the importance of input validation and the
potential risks associated with improper input handling. Encourage secure coding
practices and promote a security-conscious culture
Remember, input validation is just one layer of defense. It is essential to adopt a multi-
layered security approach that includes other security measures, such as access controls,
secure coding practices, and network security, to ensure comprehensive protection against
various types of attacks.
3.6 web application threats
Web application security is crucial to ensuring the safety and security of online systems and
their users. As more activities and transactions move online, the importance of securing web
applications becomes increasingly clear. There are various threats that web applications face,
and understanding them is essential for implementing effective security measures. Here are
some common web application threats:

1. Injection Attacks: Injection attacks occur when an attacker injects malicious code or
commands into an application. This includes SQL injection, where attackers
manipulate database queries, and command injection, where they execute arbitrary
commands on the server.
2. Cross-Site Scripting (XSS): XSS attacks involve injecting malicious scripts into web
pages viewed by other users. This allows attackers to steal sensitive information,
perform unauthorized actions on behalf of users, or deface websites.
3. Cross-Site Request Forgery (CSRF): CSRF attacks trick authenticated users into
unknowingly performing malicious actions on a website. Attackers exploit the trust
between a user's browser and a website to perform unauthorized actions.
4. Sensitive Data Exposure: This threat occurs when sensitive information, such as
passwords or credit card details, is not properly protected. Attackers can intercept or
access this data, leading to identity theft or financial loss.
5. Broken Authentication and Session Management: Weak authentication
mechanisms, session management flaws, or improper handling of session tokens can
allow attackers to hijack user sessions, impersonate users, or gain unauthorized access
to sensitive data.
6. Security Misconfigurations: Misconfigurations in web servers, frameworks, or
application components can create vulnerabilities that attackers can exploit. These
include default or weak configurations, unnecessary services or features, or improper
access controls.
7. Insecure Direct Object References: Insecure direct object references occur when an
application exposes internal implementation details, such as database keys or file
paths, in URLs or parameters. Attackers can manipulate these references to access
unauthorized resources.
8. Unvalidated Redirects and Forwards: Attackers can exploit unvalidated redirects
and forwards to trick users into visiting malicious websites or performing unintended
actions. This can lead to phishing attacks or the execution of unauthorized actions.
Preventive Measures for Web Application Threats
To mitigate web application threats, it is important to implement robust security measures.
Here are some preventive measures:

1. Input Validation and Sanitization: Thoroughly validate and sanitize user input to
prevent injection attacks and XSS vulnerabilities. Use input filtering, parameterized
queries, and output encoding to ensure that user input is safe and does not execute
malicious code.
2. Secure Authentication and Session Management: Implement strong authentication
mechanisms, such as multi-factor authentication, and ensure secure session
management practices, including session expiration and token handling.
3. Regular Security Patching and Updates: Keep web servers, frameworks, and
application components up to date with the latest security patches and updates. This
helps address known vulnerabilities and reduces the risk of exploitation.
4. Secure Configuration: Follow secure configuration practices for web servers,
frameworks, and application components. Disable unnecessary services, use secure
default configurations, and apply access controls to limit exposure.
5. Security Testing and Code Reviews: Conduct regular security testing, including
penetration testing and vulnerability assessments, to identify and address potential
vulnerabilities. Perform code reviews to ensure secure coding practices are followed.
6. Web Application Firewalls (WAF): Implement a WAF to monitor and filter
incoming web traffic, blocking known attack patterns and providing an additional
layer of defense against web application threats.
7. User Education and Awareness: Educate users about common web application
threats, such as phishing attacks and the importance of strong passwords. Encourage
them to report suspicious activities and practice good security hygiene.
Remember, web application security is an ongoing process. It requires a combination of
preventive measures, regular monitoring, and timely response to emerging threats to ensure
the safety and security of web applications and their users.
3.7 Web Application Hacking
Web application hacking or web app hacking is the act of exploiting vulnerabilities and
weaknesses in web applications to gain unauthorized access, manipulate data, or perform
malicious activities. It involves identifying security flaws in web apps and leveraging them
to compromise their integrity, confidentiality, or availability.
Web applications are software programs that run on web servers and are accessed through
web browsers. They are used for various purposes, such as online banking, e-commerce,
social media, and more. However, these applications often have security vulnerabilities that
can be exploited by hackers.
Common Web App Attacks
There are several common web application attacks that hackers often exploit to compromise
the security of web applications.
Here are some of the most prevalent ones:
1. Cross-Site Scripting (XSS)
XSS attacks involve injecting malicious scripts into web pages viewed by other users. This
can occur when the application fails to properly sanitize user input or output, allowing
attackers to execute arbitrary code in the victim's browser. XSS attacks can be used to steal
sensitive information, hijack user sessions, or deface websites.
2. SQL Injection
SQL injection attacks occur when an attacker manipulates a web application's database
queries by inserting malicious SQL code. This can enable unauthorized access to the
database, data theft, or modification of data. SQL injection vulnerabilities commonly arise
when user input is not properly validated or sanitized before being used in database queries.
3. Cross-Site Request Forgery (CSRF)
CSRF attacks trick authenticated users into unknowingly executing unwanted actions on a
web application. This is achieved by crafting malicious requests and exploiting the trust
placed in the user's browser sessions. CSRF attacks can lead to actions being performed
without the user's consent, such as changing passwords, making financial transactions, or
deleting data.
4. Remote File Inclusion (RFI) and Local File Inclusion (LFI)
RFI and LFI attacks involve exploiting vulnerabilities that allow the inclusion of external or
local files in a web application. Attackers can manipulate these vulnerabilities to execute
arbitrary code, read sensitive files, or gain unauthorized access to the server.
5. XML External Entity (XXE) Attacks
XXE attacks target applications that parse XML input insecurely. By exploiting this
vulnerability, attackers can retrieve sensitive information, execute remote code, or perform
denial-of-service attacks.
6. Server-Side Request Forgery (SSRF)
SSRF attacks occur when an attacker tricks a web application into making requests to other
internal or external resources on behalf of the application server. This can lead to
unauthorized access to internal systems, data leakage, or further exploitation of
vulnerabilities.
7. File Upload Vulnerabilities
Insecure file upload functionalities can be abused by attackers to upload malicious files onto
a server. These files can then be executed to gain unauthorized access, escalate privileges, or
perform other malicious activities.
8. Session Hijacking and Session Fixation
These attacks target weaknesses in session management mechanisms. Session hijacking
involves stealing or impersonating valid user sessions, while session fixation involves forcing
a user to use a predetermined session ID. Both attacks can lead to unauthorized access to user
accounts and sensitive data.
Web Application Hacking Methodology
The methodology for web application hacking in ethical hacking typically follows a
systematic approach to identify vulnerabilities, exploit them, and assess the impact of the
attack.
Here is a step-by-step process for web application hacking methodology:
1. Reconnaissance
Gather information about the target application, its infrastructure, and the technologies used.
This can include identifying the application's URL, server details, application frameworks,
and any associated subdomains.
2. Mapping and Discovery
Explore the target application to identify all available entry points, such as input fields,
forms, URLs, and hidden parameters. Use tools like web crawlers or manual exploration to
map the application's functionality and identify potential vulnerabilities.
3. Vulnerability Scanning
Use automated scanning tools to identify common web application vulnerabilities, such as
SQL injection, XSS, CSRF, and more. These tools can help identify potential security flaws
and save time during the initial assessment.
4. Manual Testing
Perform manual testing to validate and further investigate the vulnerabilities identified in the
previous step. This involves manually crafting and injecting payloads into input fields to test
for specific vulnerabilities and their impact.
5. Exploitation
Exploit the identified vulnerabilities to gain unauthorized access, manipulate data, or perform
malicious activities. This may involve crafting and injecting malicious code, manipulating
input values, or leveraging insecure configurations to gain control over the application or the
underlying server.
6. Privilege Escalation
If access to the application is limited, attempt to escalate privileges to gain higher levels of
access. This can involve exploiting additional vulnerabilities, such as privilege escalation
vulnerabilities or misconfigured access controls, to gain administrative or root-level access.
7. Post-Exploitation
Once access has been gained, explore the compromised system or application to gather
valuable information, such as sensitive data, credentials, or configuration details. Maintain
persistence within the system, if possible, to ensure continued access.
8. Documentation and Reporting
Document all findings, including vulnerabilities discovered, exploited systems, and the
impact of the attacks. Provide a detailed report with recommendations on how to mitigate the
identified vulnerabilities and improve the application's security posture.
It's important to note that web app hacking should only be performed with proper
authorization and within the bounds of the law. Ethical hackers or penetration testers
typically carry out these activities as part of security assessments to help organizations
identify and address vulnerabilities before malicious actors can exploit them.
3.8Cross Site Scripting / XSS Flaws / Countermeasures Correct Web Application Set-up
Cross-site scripting (also known as XSS) is a web security vulnerability that allows an

attacker to compromise the interactions that users have with a vulnerable application. It

allows an attacker to circumvent the same origin policy, which is designed to segregate

different websites from each other. Cross-site scripting vulnerabilities normally allow an

attacker to masquerade as a victim user, to carry out any actions that the user is able to

perform, and to access any of the user's data. If the victim user has privileged access within

the application, then the attacker might be able to gain full control over all of the application's

functionality and data.

How does XSS work?


Cross-site scripting works by manipulating a vulnerable web site so that it returns malicious

JavaScript to users. When the malicious code executes inside a victim's browser, the attacker

can fully compromise their interaction with the application.


XSS proof of concept
You can confirm most kinds of XSS vulnerability by injecting a payload that causes your

own browser to execute some arbitrary JavaScript. It's long been common practice to use the

alert() function for this purpose because it's short, harmless, and pretty hard to miss when it's

successfully called. In fact, you solve the majority of our XSS labs by invoking alert() in a

simulated victim's browser.

Unfortunately, there's a slight hitch if you use Chrome. From version 92 onward (July 20th,
2021), cross-origin iframes are prevented from calling alert(). As these are used to construct
some of the more advanced XSS attacks, you'll sometimes need to use an alternative PoC
payload. In this scenario, we recommend the print() function. If you're interested in learning
more about this change and why we like print(), check out our blog post on the subject.
As the simulated victim in our labs uses Chrome, we've amended the affected labs so that

they can also be solved using print(). We've indicated this in the instructions wherever

relevant.

What are the types of XSS attacks?


There are three main types of XSS attacks. These are:

 Reflected XSS, where the malicious script comes from the current HTTP request.
 Stored XSS, where the malicious script comes from the website's database.
 DOM-based XSS, where the vulnerability exists in client-side code rather than server-
side code.
Reflected cross-site scripting
Reflected XSS is the simplest variety of cross-site scripting. It arises when an application
receives data in an HTTP request and includes that data within the immediate response in an
unsafe way.
Here is a simple example of a reflected XSS vulnerability:

https://insecure-website.com/status?message=All+is+well.
<p>Status: All is well.</p>
The application doesn't perform any other processing of the data, so an attacker can easily

construct an attack like this:

https://insecure-website.com/status?message=<script>/*+Bad+stuff+here...+*/</script>
<p>Status: <script>/* Bad stuff here... */</script></p>
If the user visits the URL constructed by the attacker, then the attacker's script executes in the

user's browser, in the context of that user's session with the application. At that point, the

script can carry out any action, and retrieve any data, to which the user has access.

Stored cross-site scripting


Stored XSS (also known as persistent or second-order XSS) arises when an application
receives data from an untrusted source and includes that data within its later HTTP responses
in an unsafe way.
The data in question might be submitted to the application via HTTP requests; for example,

comments on a blog post, user nicknames in a chat room, or contact details on a customer

order. In other cases, the data might arrive from other untrusted sources; for example, a

webmail application displaying messages received over SMTP, a marketing application

displaying social media posts, or a network monitoring application displaying packet data

from network traffic.

Here is a simple example of a stored XSS vulnerability. A message board application lets

users submit messages, which are displayed to other users:

<p>Hello, this is my message!</p>


The application doesn't perform any other processing of the data, so an attacker can easily

send a message that attacks other users:

<p><script>/* Bad stuff here... */</script></p>


DOM-based cross-site scripting
DOM-based XSS (also known as DOM XSS) arises when an application contains some
client-side JavaScript that processes data from an untrusted source in an unsafe way, usually
by writing the data back to the DOM.
In the following example, an application uses some JavaScript to read the value from an input

field and write that value to an element within the HTML:

var search = document.getElementById('search').value;


var results = document.getElementById('results');
results.innerHTML = 'You searched for: ' + search;
If the attacker can control the value of the input field, they can easily construct a malicious

value that causes their own script to execute:

You searched for: <img src=1 onerror='/* Bad stuff here... */'>
In a typical case, the input field would be populated from part of the HTTP request, such as a

URL query string parameter, allowing the attacker to deliver an attack using a malicious

URL, in the same manner as reflected XSS.

What can XSS be used for?


An attacker who exploits a cross-site scripting vulnerability is typically able to:

 Impersonate or masquerade as the victim user.

 Carry out any action that the user is able to perform.

 Read any data that the user is able to access.

 Capture the user's login credentials.

 Perform virtual defacement of the web site.

 Inject trojan functionality into the web site.

Impact of XSS vulnerabilities


The actual impact of an XSS attack generally depends on the nature of the application, its

functionality and data, and the status of the compromised user. For example:

 In a brochureware application, where all users are anonymous and all information is

public, the impact will often be minimal.

 In an application holding sensitive data, such as banking transactions, emails, or

healthcare records, the impact will usually be serious.


 If the compromised user has elevated privileges within the application, then the

impact will generally be critical, allowing the attacker to take full control of the

vulnerable application and compromise all users and their data.

How to find and test for XSS vulnerabilities


The vast majority of XSS vulnerabilities can be found quickly and reliably using Burp Suite's
web vulnerability scanner.
Manually testing for reflected and stored XSS normally involves submitting some simple
unique input (such as a short alphanumeric string) into every entry point in the application,
identifying every location where the submitted input is returned in HTTP responses, and
testing each location individually to determine whether suitably crafted input can be used to
execute arbitrary JavaScript. In this way, you can determine the context in which the XSS
occurs and select a suitable payload to exploit it.
Manually testing for DOM-based XSS arising from URL parameters involves a similar

process: placing some simple unique input in the parameter, using the browser's developer

tools to search the DOM for this input, and testing each location to determine whether it is

exploitable. However, other types of DOM XSS are harder to detect. To find DOM-based

vulnerabilities in non-URL-based input (such as document.cookie) or non-HTML-based sinks

(like setTimeout), there is no substitute for reviewing JavaScript code, which can be

extremely time-consuming. Burp Suite's web vulnerability scanner combines static and

dynamic analysis of JavaScript to reliably automate the detection of DOM-based

vulnerabilities.

How to prevent XSS attacks


Preventing cross-site scripting is trivial in some cases but can be much harder depending on

the complexity of the application and the ways it handles user-controllable data.

In general, effectively preventing XSS vulnerabilities is likely to involve a combination of the

following measures:

 Filter input on arrival. At the point where user input is received, filter as strictly as

possible based on what is expected or valid input.


 Encode data on output. At the point where user-controllable data is output in HTTP

responses, encode the output to prevent it from being interpreted as active content.

Depending on the output context, this might require applying combinations of HTML,

URL, JavaScript, and CSS encoding.

 Use appropriate response headers. To prevent XSS in HTTP responses that aren't

intended to contain any HTML or JavaScript, you can use the Content-Type and X-

Content-Type-Options headers to ensure that browsers interpret the responses in the

way you intend.

Content Security Policy. As a last line of defense, you can use Content Security Policy
(CSP) to reduce the severity of any XSS vulnerabilities that still occur.

You might also like