Pattern Drive Private Limited

xss-vs-csrf XSS Vs CSRF



XSS Vs CSRF: Know The Differences & Similarities Of The Attacks

Updated on: 21/06/2022

232 Views | 0 Comments

Both the XSS and CSRF are client-side attacks that the attackers carry out. Both of them are most widely used attacks or common attacks on the websites. In this article we will discuss all possible aspects of both the attacks including how to prevent XSS and CSRF. But before we dive into the similarities and dissimilarities and the other aspects of XSS Vs CSRF, let us first know about them in detail and have a basic concept of client-side attacks and the server-side attacks.

What Is A Client Side Attack?

A client side attack can be described as any kind of cyber attack that targets the computer software or hardware, rather than the server. For instance, a client side attack takes place if a user downloads a malicious script or even clicks on a malicious link that can then infect the browser or computer of the victim. 

In total, there are six kinds of client side attacks such as:

  • XSS or Cross-Site Scripting
  • CSRF or Cross-Site Request Forgery
  • Supply Chain Attack
  • Clickjacking
  • Formjacking
  • Data Exfiltration

What Is A Server Side Attack?

Server side refers to anything that is occurring on the server instead of the end user’s device. In the short span of the history of the internet, there was a time when everything had been operated on the server side, which even included things such as the dynamic web pages. Nevertheless, the process of transmitting the data from the end user’s device (which is usually the client side) took longer, which is something that is termed as latency. In order to combat this problem, the web developers had started to build code or scripts that operated more on the client side that made the web page operations much faster.

What Is XSS?

XSS is also known as Cross-Site Scripting. It is a web security vulnerability that permits an attacker to compromise the interactions that the users possess with a vulnerable application. The attacker is permitted to avoid the same origin policy that is designed to segregate the different websites. Usually, the XSS vulnerability permits the attacker to disguise as a victim user for performing any action that the user is able to perform. This helps them to access any of the user’s data. 

The attacker might also be able to receive complete control over all of the data and functionality of the application’s data if the victim user possesses privileged access within the application. The victims of the XSS attacks include some of the big names such as Twitter, eBay and Yahoo!

Types Of XSS Attacks

Broadly, there are three primary kinds of XSS Attacks or Cross-Scripting attacks:

1. Persistent XSS Attacks (Stored Attacks)

These kinds of XSS attacks include such attacks where the malicious code is permanently stored on the target website, usually in its database, visitor logs, comment fields, message forums etc. When the user requests this information from the web server, then they unknowingly retrieve the malicious script. This kind of cross-site scripting attack is also known as Stored XSS.

2. Non-persistent XSS Attacks (Reflected Attacks)

Dissimilar to the persistent XSS attacks, with the non-persistent XSS attacks, the malicious code is never permanently stored on the web server. Instead of this, the code is reflected off the server and is then delivered to the victim user through either an email message or another website. When the user performs a legitimate action, like submitting a form, browsing an infected website, clicking on a malicious link, then the malicious code travels to that website and reflects back to the browser of the victim.

3. DOM-based Cross-Site Scripting

The DOM based XSS, also termed as DOM XSS, occurs when an application contains some client side JavaScript that processes the data from an untrusted source in a pretty unsafe method, usually by writing the data back to the DOM. Following is an example where an application makes use of some JavaScript for reading the value from an input field and then 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 is able to control the value of the input field, they can very easily construct a malicious value that results in the execution of their own script:

You searched for: <img src=1 onerror="/* Bad stuff here... */">

In an usual case, the input field would be populated from part of the HTTP request like the URL query string parameter permitting the attacker to deliver an attack making use of a malicious URL just the same way as the reflected XSS.

How Does Cross-Site Scripting or XSS Work?

A typical XSS attack possesses two stages, viz:

  1. For running the malicious JavaScript code in the browser of the victim, the attacker needs to find a way to inject the malicious code to a web page that the victim visits quite often. 
  2. Following the injection of the malicious code, the victim is required to visit the webpage with that code. If the attack has been directed at specific victims, phishing and/or social engineering can be used for sending malicious URLs to the victim. 

Example of XSS

The following snippet of the server side pseudo code has been used for displaying the most recent comment on a web page:

<h1>Most recent comment</h1>

The above script takes the recent comment from a database and also inserts it into an HTML page. It assumes that the comment comprises only text, devoid of the HTML tags or the other code. What exactly makes it vulnerable to XSS is permitting the attacker to submit a malicious payload within a comment such as:

<img src="x" onerror="alert(1)">
<button onclick="alert(document.domain)">
<a onmouseover="prompt(1)">xss</a>

The web server also offers the following HTML code to the users that visit this particular web page:

    <h1>Most recent comment</h1>

The malicious code also executes as soon as the page is loaded in the browser of the victim. Most often, the victim is unable to obstruct such an attack as it is quite hard to even realize that the attack is in operation. 

Why Is XSS Used?

An attacker who is able to exploit the cross-site scripting vulnerability is typically able to do the following:

✅ Capture the login credentials of the users.

✅ Carry out any sort of action that the user is able to perform.

✅ Inject the trojan functionality into the website. 

✅ Masquerade or impersonate as the victim user.

✅ Perform virtual defacement of the website. 

✅ Read all kinds of data that the user is able to access.

Impact Of The XSS Vulnerabilities

The original impact of an XSS attack usually depends on the application nature, its functionality, the data and the status of the compromised user. For instance,

✅ In a brochureware application, where all of the users are anonymous and all the information is public, often the impact will be minimal.

✅ In an application that holds the sensitive data like emails, banking transactions or healthcare records, usually the impact will be serious. 

✅ If the compromised user possesses elevated privileges within the application, then generally the impact will be critical that permits the attacker to take complete control of the vulnerable application and compromise all the users as well as their data.

How To Detect & Prevent XSS Attacks?

The diverse majority of the XSS vulnerabilities can be discovered quickly and also reliably making use of a tool called Burp Suite, which is a Web Vulnerability Scanner. The other examples include Acunetix and Nessus

In order to manually test for the stored and reflected XSS, submission of some simple unique input like a short alphanumeric string into each entry point in the application is done. In addition to this, it also involves identifying individual locations where the submitted input is returned in the HTTP responses and individually testing each location to determine if suitable crafted input can be used to execute the arbitrary JavaScript. In such a method, one can actually determine the context in which the XSS occurs as well as select a suitable payload in the bid to exploit it. 

On the other hand, manually testing for the DOM-based XSS rising from the URL parameters involves just the similar process. This includes placing some simple unique input in the parameter, making use of the browser’s developer tools to locate the DOM for this input and also testing individual location for determining if it is exploitable. 

That being said, the other kinds of DOM XSS are much harder to detect. In order to locate the DOM-based vulnerabilities in the non-URL-based input like document.cookie or the non-HTML based sinks such as setTimeout, there is no substitute for reviewing the JavaScript code. This can be much more time consuming. The web vulnerability scanner of Burp Suite combines the dynamic and the static analysis of JavaScript for reliably automating the detection of the DOM-based vulnerabilities. 

Preventing the cross-site scripting is petty in some of the cases but can be pretty complicated depending on the application complexity and the method it handles the user controllable data. Usually, effectively preventing the XSS vulnerabilities is likely to include a combination of the below mentioned measures:

Filter Input On Arrival: This is at the point where the user input is received, you are required to filter as strictly as possible depending on what is expected or valid input. 

Encode The Data On Output: This is at the point where the user-controllable data is output in the HTTP responses, all you need to do is encode the output in the bid to prevent it from being interpreted as active content. Based on the output context, this might need applying the combinations of HTML, JavaScript, URL and CSS encoding.

What Is CSRF?

CSRF or XSRF is the abbreviated term for Cross-Site Request Forgery, also known by the other names such as Session Riding or Sea Surf. It is defined as a web security vulnerability that successfully tricks a web browser into executing any unwanted action. Accordingly, the attacker also abuses the trust that a web application possesses for the browser of the victim. It also permits an attacker to partly bypass the same-origin policy that is meant to prevent the different websites from interfering with each other. 

How Does Cross-Site Request Forgery or CSRF Work?

For conducting a successful CSRF attack, the attacker will typically make use of the social engineering like an email or link that will trick a victim into sending a forger request to a server. Since the user is already authenticated by their application at the time of occurrence of the attack, it is just impossible for the application to differentiate a legit request from a forged one.

For a CSRF attack to be successful, the following are the three key conditions that must be in place:

Relevant Action - Privileged action or any action on the user specific data.

Cookie Based Session Handling -  The action performing involves issuing one or several HTTP requests and then the application depends only on the session cookies for identifying the user who has made the request. No other mechanism is in place for validating the tracking sessions or the user requests. 

No Unpredictable Request Parameters - The request does not contain any of the parameters and the value of those cannot be determined or guessed by the attacker.

Example of CSRF

Suppose the website of your bank offers a form that permits transferring funds from the user that is logged in to a different bank account. For instance, the HTTP request might seem as the following

POST /transfer HTTP/1.1
Cookie: JSESSIONID=randomid;; Secure; HttpOnly
Content-Type: application/x-www-form-urlencoded

Now suppose you authenticate to the website of your bank and you visit any evil website without logging out from the bank’s website. The malicious website contains a HTML page that possess the following form:

<form action='' method='post'>
    <input type='hidden' name='amount' value='100.00'/>
    <input type='hidden' name='routingNumber' value='evilsRoutingNumber'/>
    <input type='hidden' name='account' value='evilsAccountNumber'/>
    <input type='submit' value='Win Money!'/>

If you like winning some cash and you click on the “submit” button. You have actually transferred $100 to a malicious user in process unintentionally. So you must wonder how this happened. While the malicious website just could not see your cookies, all those cookies that are associated with your bank are being sent along with the request. 

How To Prevent CSRF Attacks?

An attacker can launch a CSRF or Cross-Site Request Forgery Attack when he is aware of the parameters and the value combinations that are being used in the form. Thus, by adding an extra parameter with an unknown value that the attacker is unaware of and validating by the server, you can actually prevent CSRF attacks. Following are some of the most effective methods to prevent the CSRF attacks or block the cross-site request forgery attacks.

Implementation Of An Anti-CSRF Token

An anti-CSRF token is a kind of server-side CSRF protection. It is just a random string that is solely known to the user’s browser and the web application. The anti-CSRF token is usually stored inside a session variable, On a page, typically it is in a hidden field that has been sent with the request. 

If the values of the hidden form field and the session variable match, then the web application successfully accepts the request. If it is otherwise, the request is instantly dropped. In such a case, the attacker is unaware of the exact value of the hidden form field that is required for the request to be accepted. Thus, he is unable to launch the CSRF attack. Additionally, owing to the same origin policy, the attacker cannot even read the response that comprises the token.

✅ Usage Of The SameSite Flag In Cookies

The SameSite flag in the cookies is apparently a new method of preventing CSRF attacks as well as improving the web security. The session cookie used by the attacker is unique for each user. Thus, the web application uses it for distinguishing the users and also to determine if they are logged in. 

Vulnerability Classification & Severity Table

Below is a tabular form of the vulnerability classification and its severity:


ID / Severity

PCI v3.2


OWASP 2013


OWASP 2017














XSS Vs CSRF: How Are Both Of Them Different?

The major difference between XSS and CSRF considering XSS Vs CSRF is that a CSRF attack is in need of an unauthenticated session while the XSS attacks does not require the same. Some of the other differences include:

➤ As XSS does not require any user interaction, it is believed to be even more dangerous.

➤ The CSRF is restricted to the actions that the victims can perform. On the other hand, XSS works on the execution of the malicious scripts widening the scope of actions that the attacker can perform.

➤ The XSS solely seeks for a vulnerability while the CSRF requires a user to access the malicious page or even a link to click. 

➤ CSRF works just one way. It can just send HTTP requests, but cannot view the response. On the contrary, XSS can send and receive the HTTP requests and also responses in the bid to extract the required data. 

Below is a summary of the XSS vs CSRF Attack differences:

XSS Vs CSRF (Source: Geeks For Geeks)

Is It Possible To Prevent XSS Attacks Using CSRF Tokens?

Some of the XSS attacks can be restricted via the effective use of CSRF tokens, A simple XSS vulnerability that can be trivially exploited like the following can be considered:<script>/*+Bad+stuff+here…+*/</script>

Now, consider the following piece of code if the vulnerable function includes a CSRF token.<script>/*+Bad+stuff+here...+*/</script>

If the server validates the token properly and rejects the requests without a valid CSRF token, then the token will prevent exploitation of the XSS vulnerability. The reflected form of the XSS involves a cross-site request. By restricting the malicious user from forging a cross-site request, the application prohibits trivial exploitation of the XSS vulnerability.

Here are some of the important warnings that arises:

✅ If a reflected XSS vulnerability is located anywhere else on the website in a function that is not at all protected by a CSRF token, then the XSS can be exploited in the normal way.

✅ An exploitable vulnerability located anywhere on the website can be leveraged for making the victim user perform actions even if those actions are not at all protected by the CSRF tokens. 

✅ The CSRF tokens do not protect against the stored XSS. If a page protected by a CSRF token is also the output point for a XSS vulnerability that is stored. Then that XSS vulnerability can be exploited in the usual method.

Can CSRF Protection Be Bypassed With An XSS Attack?

Making use of the XSS, one can bypass the CSRF protection and thus can automate any action that anybody can do on the application without any issue.

The basic CSRF POST attack can look something like this:

<form  id='myform' action='http://localhost/csrf/login.php' method='post'>
    <input type='hidden' name='token' value='unkown_csrf_token' />
    <input type='text' name='name' value='evilUser'><be>
    <input type='submit' value='Submit'>

The attacker would inject this code on a website and then attempt to trick a victim into visiting it to conduct XSS to CSRF bypass. Owing to the CSRF protection, this would not work. Thus, the result will be:

wrong token given: unknown_csrf_token expected: 4baabea60e7683f9feb54086cebda4e4

Now, if the attacker introduces an XSS vulnerability to the website, he will be able to perform the CSRF attacks. The XSS vulnerability does not have to be in the same script as the form is:

// /var/www/csrf/search.php
        <?php echo $_GET['s']; ?>

Now, it is easier for the attacker to bypass CSRF protection via the XSS. He would first acquire the valid token from the form, create the attack from with the retrieved token and then submit the form:

var csrfProtectedPage = 'http://localhost/csrf/login.php';
var csrfProtectedForm = 'form';
// get valid token for current request
var html = get(csrfProtectedPage);
document.body.innerHTML = html;
var form = document.getElementById(csrfProtectedForm);
var token = form.token.value;
// build form with valid token and evil credentials
        += '<form id='myform' action='' + csrfProtectedPage + '' method='POST'>'
        + '<input type='hidden' name='token' value='' + token + ''>'
        + '<input id='username' name='name' value='evilUser'>'
        + '</form>';
// submit form
function get(url){
    var xmlHttp = new XMLHttpRequest();'GET', url, false);
    return xmlHttp.responseText;

Following this, the attacker would inject this script on a server under his control. For instance,


Next, he would trick the victim into visiting the following:

http://localhost/csrf/search.php?s=<script src='https://localhost/csrf/script.js'></script>

The malicious JavaScript is not required to be hosted on the server of the victim. The script would be executed in the context of the website of the victim itself while the attacked form would be submitted in the name of the victim user. The result in the debug file would be:

issuing token: 8c168479619c9dbcbfa1cdef5e93daf8
token ok: evilUser

The value of the evilUser that is controlled by the attacker would be submitted by the victim himself. 

In an original attack, the victim would remain unaware of all the occurrences as the attacker will be able to load as well as execute the malicious JavaScript in an iframe and possibly redirect the victim to an innocent page. 

Can CSRF Tokens Be Stolen?

There are various web vulnerabilities that the attackers can exploit. If you are quite familiar with the severity of the crime, you will know how essential it is to secure both the sensitive data and the devices. The CSRF token in this aspect is a well known part of cybersecurity for which some of the users are still skeptical regarding its confidentiality.

That being said, it is quite difficult to steal the CSRF tokens. It takes a tech-savvy and determined attacker to crack it. And even in this scenario, it might take a while to do so. However, the best hackers can always outsmart the system, but it is not commonplace. These secret codes are the server-application generated ones and that the system sends you.

It will be best if you place the CSRF token strategically so that the attackers will not be able to access it. The experts always recommend that you place it before an HTML document. This will minimize any vulnerability that the attackers might capitalize on to invade your server. Additionally, it is advisable that you must avoid transmitting all of these secret codes within the cookies in your browser. 


In the XSS Vs CSRF attacks and the XSS CSRF example, it has been seen that both of them are serious security vulnerabilities. The Cross Site Request Forgery is an attack where the malicious hackers pose as the actual users of a specific website and trick the system into trusting that it is performing a legit action. Thus, the developers have created a system where the server produces a unique user-specific token called the CSRF token. If the user does not enter the value or if the value is the incorrect one, then the system will immediately shut down and also decline the access. 

The malicious hackers will not be able to guess or even generate valid information as it is a significant as well as randomly generated digit. It is just a few tech-savvy hackers who are able to steal and use these CSRF tokens. 

It is also seen that the XSS attacks or the Cross-Site Scripting attacks are continuously on the rise as millions of the users log onto various websites each day. Plus, the attackers also find more smart means to make use of JavaScript as well as the other forms inthe bid to obtain sensitive information. It is quintessential to be on the lookout all the time not to fall for their schemes. 

The best remedy for this is to set up a Web Application Firewall (WAF) that will ensure you are safe at all times, not solely from XSS but also from the other dangerous infiltrations. You must also note that when you are victimized by a trap, you can always mitigate such a situation by locating the code and also starting a clean slate. In some other article we will discuss XSS vs CSRF vs CORS.


Leave a Comment

By Submitting you agree to our Terms of Service and Privacy Policy.