CSRF vs XSS – What Makes Cross-Site Request Forgery and Cross-Site Scripting Attacks Different?

Sheheryar Ali Baig & Sahar Butt
Sheheryar Ali Baig & Sahar Butt

December 1, 2022

CSRF vs XSS – What Makes Cross-Site Request Forgery and Cross-Site Scripting Attacks Different?

The best way to deal with cybersecurity attacks is to remain aware of their different types. One of these types is client-side cybersecurity threats, i.e. when a user downloads malicious content. 

What happens after the user downloads malicious content? In most cases, we hear about security breaches, losing access to our accounts, and witnessing further malicious activity on our websites.

When it comes to client-side attacks, the two most common types are CSRF and XSS attacks. What are CSRF vs XSS attacks? Why should you know about them? In this blog, we shall go over the definitions, differences, working, and prevention methods for Cross-Site Request Forgery and Cross Site Scripting Attacks.

CSRF vs XSS Attacks – In Summary

XSS AttacksCSRF Attacks
XSS is the abbreviation for Cross-Site Scripting.CSRF is the abbreviation for Cross-Site Request Forgery.
The corrupted script is introduced in the client-specific website script.The site users may end up injecting the corrupted HTTP requests to the targeted site, without being aware of the outcome.
Random and unauthenticated data is introduced bit by bit.The success of a CSRF attack depends on the browser’s features. A CSRF attack may only succeed if the browser can process the attack bundle.
JavaScript is entirely responsible for XSS attacks.CSRF attacks may not always require JavaScript.
The target site is sent the corrupted code for processing.The troublesome code is stored on third-party websites rather than the main site.
A website that has an XSS vulnerability can be susceptible to a CSRF attack as well.A website that has suffered from a CSRF attack may not be necessarily prone to an XSS attack.
XSS attacks are quite harmful and nefarious.CSRF attacks are not as destructive.
Once an XSS attack is successful, the hacker can exploit it in any manner possible.Hackers have limited ability to exploit and can only cause damage up to the capacity of the URL.
XSS attacks prove to be much more dangerous.CSRF attacks are not as dangerous as XSS attacks.

What is CSRF & How Does it Work?

CSRF or Cross-Site Request Forgery Attacks involve tricking the users into performing an action on behalf of the hacker. The user is not aware of the action they are performing, such as clicking a link or loading a page attached to a malicious request. 

CSRF attacks are also known as session-riding attacks or one-click attacks. It relies on a verified user to attack a website and does not take over the service provider directly. As such, for a CSRF attack, the hacker must take assistance from someone verified or authenticated for accessing a server and then deliver malicious content to the user. It involves the usage of social engineering techniques to convince the user to perform an action. 

The aim of a hacker in a CSRF attack is to bypass the origin policy, which prevents one website from interfering with another website.

How does CSRF Work?

When you are using a small program or utility, your browser sends multiple HTTP requests while you’re working, such as clicking or typing a URL on the address bar. The HTTP requests are sent while your usage is explicit and hence in the known.

Similarly, your browser is dispatching implicit HTTP requests too for strategizing the code on the web page. An example is loading an image on a webpage using a separate HTTP request. You did not explicitly perform any action to load the image except scroll or browse around the page.

Such implicit requests may also be directed to domains that have nothing to do with the location of the page you are viewing. For example, an image displayed on venturedive.com may come from example.com. 

What matters in such cases is that the requests to both locations come from the same browser, so your current authentication method (whether it’s a session cookie or another method) applies to both locations. As such, if your browser opens actualwebsite.com and loads an image from example.com, it will create a user session on example.com, and the web application for example.com will consider you as an authenticated user (even though you originally opened actualwebsite.com, not example.com).

With these conditions in place, the attacker can construct a web page containing the following HTML:


If a victim user visits the attacker’s internet web page, the following will happen:

  • The attacker’s page will trigger an HTTP request to the vulnerable website.
  • If the consumer is logged in to the prone web website, their browser will mechanically encompass their consultation cookie inside the request (assuming SameSite cookies aren’t getting used).
  • A website that is not secured will put the request in normal behavior and treat it as having been made by the victim user and change their email address.

cross site request forgery infographic

Limitations to Cross-Site Request Forgery

For a cross-site request forgery attack to happen and succeed, several conditions must be met. These conditions act as limitations to a successful CSRF attack and are as follows:

  • The targeted site should not test the referrer header or the victim with a browser or plugin that permits referrer spoofing.
  • The attacker ought to find a form submission at the goal site or a URL that has side results that do something (e.g., transfer money or modify the victim’s email address or password).
  • The attacker should decide the right values for all the bureaucracy or URL inputs; if any of them are required to be secret authentication values or IDs that the attacker cannot guess, the assault will most likely fail (unless the attacker is extremely fortunate in their bet).
  • It is essential for the attacker to trap the victim on an internet web page with malicious code while the user is logged into the target website online.
  • To access the aimed website, the threat actor must trespass the user authentication.
  • Absence of unpredictable request parameters: the request has values that can be guessed easily.
  • Cookie-based session handling: this includes issues with many HTTP requests. Since the application only relies on session cookies for identifying who made the requests, there is no other method for validating user requests or tracking sessions.
  • The assault is blind: the attacker cannot see what the target website sends returned to the victim in reaction to the forged requests until they make the most of a move-web page scripting or other malicious programs on the target internet site. Similarly, the attacker can most effectively target any hyperlinks or put up any paperwork that arises after the solid preliminary request if those subsequent links or forms are similarly predictable. (Multiple objectives can be simulated by including multiple photos on a page or by using JavaScript to introduce a put-off between clicks.)

Prevention Against Cross-Site Request Forgery (CSRF)

Few powerful techniques exist for both the prevention and mitigation of CSRF assaults. It is better to implement prevention techniques beforehand, such as safeguarding login credentials and denying unauthorized actors the right to enter the programs.

Some of the best practices include:

  • Logging off web applications when not in use
  • Securing usernames and passwords
  • Not allowing browsers to remember passwords
  • Avoiding simultaneous browsing while logged into an application

For internet applications, multiple solutions exist to block malicious site visitors and save the user from attacks. Some of the most common mitigation techniques are to generate random tokens for every consultation request or identity.

CSRF Tokens: What Are They and How Do They Help?

These tokens are eventually checked and proven by way of the server. Session requests having both reproduction tokens and missing values are blocked. Instead, what happens is that if a request received does not match its consultation ID, it is prevented from accessing an application.

Double submission of cookies is another well-known technique to block CSRF. Much like the use of tokens, random tokens are assigned to each cookie and a request parameter. The server then verifies that the tokens match before granting entry to the software. 

Even as powerful as they are, tokens can be uncovered by several factors, which include browser records, HTTP log files, network home equipment logging the first line of an HTTP @request, and referrer headers if the protected web page links to an external URL. These potential weak spots make token solutions less than full-proof solutions. 

How to Prevent CSRF Attacks?

The primary approach to protecting against CSRF assaults is to create a way for the web utility to distinguish between legitimate requests (made on behalf of that application) and potentially malicious ones. The following two strategies are the most common:

 1.    Anti-CSRF Tokens

You send a unique token with every legit token and validate it while receiving requests. This anti-CSRF token, also referred to as a synchronizer token, is generated at the server aspect, and attackers do not have any way of understanding its correct order. The correct order is only acknowledged by the internet application and the browser. Requests dispatched as CSRF attacks will not have a legitimate token, which allows the application to ignore them as invalid, log them as attack attempts, or maybe raise the alarm.

As soon as you have generated an anti-CSRF token, it is hidden in a unique header for each request. Also, anti-CSRF tokens need to be used now for every form in the authenticated sector of the web software, as well as for unauthenticated login bureaucracy, APIs, and AJAX requests (XMLHttpRequest).

You can generate anti-CSRF tokens safely via cryptographic techniques such as Paragonie anti-CSRF for your personal home page. It is suggested that you use libraries rather than developing your own code, as it can be more susceptible to errors and harder to update.

Note: Many modern development frameworks already have synchronizer tokens built in, and their CSRF protection is often limited to HTTP methods (for requests that change the state). This means that GET requests are usually not protected. Therefore, if a developer creates state-changing features that take their entry from GET requests (not recommended in programming), these requests will no longer be protected by way of built-in CSRF safety.

2.    SameSite cookies

Another very effective way to differentiate valid requests from potentially dangerous ones is by searching at the origin of the request. You can trust the request if it comes from the same domain/website online, making it legitimate. If it comes from an external domain, it can be dangerous. You can use a particular cookie protection flag to take advantage of this technique.

Modern browsers guide the SameSite cookie attribute, which you may use when setting your consultation cookies. This may have one of three settings:

  1. Lax: a more relaxed form of cross-site request protection wherein the browser does not send cookies for pass-website subrequests.
  2. Strict: a stricter form of CSRF prevention. The browser only sends cookies in a first-party context, not with all the requests that third-party websites have initiated.
  3. None: Cookies are sent by the browser in all contexts; however, you should set the comfortable attribute to prevent the browser from blocking the cookie.

While the latest browsers set the SameSite characteristic to Lax by default for all cookies, we suggest you manually set it in your web utility (to Lax or Strict, depending on whether you need CSRF subrequests or not). 

What is Cross-Site Scripting (XSS) & How Does it Work? 

Cross-site scripting attacks – abbreviated “XSS” attacks, involve the injection of malicious code into otherwise trustworthy websites. An online scripting assault happens when cybercriminals inject malicious scripts into the focused website’s content material, which is then protected with dynamic content material introduced to the victim’s browser. The sufferer’s browser cannot understand that the malicious scripts cannot be trusted and therefore executes them. In extreme cases, you may eventually consult a QA to detect these scripts.

Cross-site scripting works by manipulating a vulnerable internet site so that it returns malicious scripts to customers. Often, this involves JavaScript; however, any purchaser-aspect language can be used. Cybercriminals target websites with prone features that are given personal input –which include seeking bars, remark boxes, or login paperwork. The criminals connect their malicious code to the pinnacle of the legitimate internet site, essentially deceiving browsers into executing their malware every time the web page is loaded.

A successful attack can have the following outcomes:

  • User files are revealed or disclosed
  • Sensitive information is made accessible
  • A malware or Trojan horse is installed in the computer
  • Online banking information is exposed
  • The HTML/DOM content is modified
  • Users are redirected to unknown and spammy websites
Cross Site Scripting Attack infographic

XSS Attack Example

The following pseudo-code can be used for displaying the last comment on a webpage, such as in a forum:


print “<html>”

     print “<h1>Most recent comment</h1>

            print database.latestComment

print “</html>

After taking this last comment, the attacker inserts it into an HTML page. Assuming that the comment is only text-based without any HTML tags, it is vulnerable to XSS, and then the attacker can submit a malicious payload in a comment. For example;


The users will be provided with this HTML code when the users will visit:


<html>

     <h1>Most recent comment</h1>

            <script>doSomethingEvil();</script>

</html>

Once the page is loaded, this malicious script is loaded in the browser of the targeted victim.

Types of XSS Attacks

1.    Reflected/Non-Persistent XSS Attacks

Non-Persistent or Reflected Cross-Site Scripting is the most common type of XSS attack. It makes use of data provided by a web client such as in HTML form submission. The server-side scripts then parse the data and display a page result for the user without sanitizing or examining the script. The script can also be delivered to the user through an email message, spam link, or other external route.

2.    Stored XSS Attacks/Persistent XSS/Type-I XSS Attacks

The malicious code is injected and permanently stored in different parts of a web application, which includes comment threads, visitor logs, forums, databases, etc. Every time a user visits such an infected website, the malicious script will be executed in the browser of the user.

The attacker will save some data in the server and display it on ‘normal’ pages without proper HTML escaping. These are much more dangerous than non-persistent or reflected XSS attacks.

3.    Blind XSS Attacks

A blind XSS attack is a hybrid XSS attack. Here, the script of the attacker is stored in the backend application. As the name suggests, Blind XSS attacks are a type of persistent attack that depends on the vulnerability of the code of the website. Login forms and forums/message boards are the most common targets of Blind XSS attacks.

4.    DOM-based XSS Attacks

Document Object Model-based – DOM-based XSS Attacks or Type-0 XSS Attacks are a unique type, wherein the webpage does not change but its code operates differently. Here, the modification occurs in the browser’s Document Object Model environment, hence the name DOM-based XSS attacks. The HTTP response is not changed, but due to modifications in the DOM, the client’s side code is executed differently.

Type-0 XSS Attacks cannot be identified without proper penetration testing. They can only be removed via client-side HTML sanitization, for which you might have to opt for outsourced QA services.

How to Prevent XSS Attacks?

To help prevent XSS attacks, you can follow the listed techniques:

1.    Keep your software updated

Outdated software cannot protect you against new types of vulnerabilities, making it prone to XSS attacks. Keep all your software always updated.

2.    Validate User Input

Screen input fields on arrival. Anything originating data externally or outside of your system should not be trusted instantly, and it should always be checked for malicious scripts. Make and use an “allow list” of data that can pass, like good input, acceptable, and known. On the output, encode data to prevent it from being interpreted as active content. You will require combinations of HTML, CSS, JavaScript, and URL encoding for this.

3.    Sanitize Data

Examine all data and remove whatever data you find unwanted, including suspicious HTML tags. From the safe data, remove unsafe characters.

4.    Use a Web Application Firewall

A web application firewall or WAF will make use of different techniques to encounter XSS attacks, SQL injection, cookie poisoning, and others. It can help prevent XSS attacks since it uses signature-based filtering to identify and block malicious requests.

5.    Use QA services

Some XSS attacks cannot be prevented by your efforts alone and, in fact, require the assistance of experts, such as for security testing. In these cases, you have to partner with quality assurance engineers and consultants to avoid high-level vulnerabilities.

Can CSRF tokens prevent XSS attacks?

You can prevent Reflected XSS attacks using a CSRF token. For other forms of XSS attacks, they are not as helpful because the vulnerabilities may exist in the application and the users will be tricked into performing a malicious action anyway.

Conclusion – CSRF vs Attacks: Should You Remain Careful?

Cyberattacks are growing increasingly common, which means you need to remain beware of the vulnerabilities existing on your site. While you may not see any major differences between CSRF and XSS or find them as threatening, it is imperative that you always remain alert and partner with credible QA services to keep protection to the fullest. 

Are you planning to create a top-quality digital solution? Talk to our experts now!

You might also like…