Understanding CSRF Attacks And Locking Down CSRF Vulnerabilities

Published 9 November 2023
Updated 4 December 2023
Mart Virkus
Head of Marketing
Table of Contents

Remaining committed to protecting the security and privacy of your visitors (and users) is as important as it always has been in our eyes. 

Studies back in 2003 (yes, that’s around 20 years ago) found that there was an attack every 39 seconds on average.

And some statistics now suggest up to 30,000 websites are victims of attacks every single day. 

In other words: that would equate to ~ 30 sites since you began reading this article.

However, some attack vectors are harder to battle and protect your sites from than others, including cross-site request forgery (CSRF) attacks and vulnerabilities.

So, in this article, we’ll cover what cross-site requests are and how they can be used for either good or bad. We’ll answer the question, “What is a cross-site request forgery (CSRF) attack?”, and explain how they work. We’ll also take a look at some real-world examples of CSRF attacks.

Let’s get started!

What are Cross-Site Requests?

Cross-site requests are HTTP requests sent from one website or domain to a different website or domain. They can be used for various purposes, such as accessing or sharing resources, triggering actions, or integrating features between different websites or services.

If you want to allow users to perform actions on your website from a different domain or website, then using cross-site requests is one way to do so. Let’s see a few examples where this can be used.

  • Cross-domain authentication: You often encounter websites where you can log in to your account using credentials from another website or service, such as Google, Facebook, or Twitter. This can make the login process easier and faster for users, as they don’t need to create a separate account or password for each website.
  • Social sharing: Many websites allow users to post content to different platforms or networks, such as Instagram, Pinterest, or LinkedIn. Having the sharing functionality can increase the visibility and reach of your content, as well as the engagement and feedback from users.
  • Webhooks: These are mainly used for automated tasks that allow users to trigger actions on your website based on events that happen on another website or service, such as Stripe, Mailchimp, or Zapier. Having webhooks on your website can automate and streamline your workflows, as well as integrate your website with other tools and features.

This is a useful feature for users who want to enhance their web experience and functionality by integrating it with different websites or services. However, cross-site requests can also pose some security risks, such as cross-site request forgery (CSRF) attacks. Let’s discuss why it is a security risk if implemented improperly.

What is a CSRF Attack?

CSRF stands for Cross-Site Request Forgery, which is a type of web attack that takes over an existing session running on a website by using the session cookies stored in your browser.

Let’s break down each word in the acronym:

  • Cross-Site: This means that the attack requires two or more websites. Usually, attackers create a malicious website to send a request to a legitimate website on behalf of a user who is already logged in to the legitimate website.
  • Request: When browsing a website, you need to make HTTP requests to view content. This happens automatically as it is handled by your browser in the background. For example, an HTTP request is created when you change your password, transfer money, or delete an account on a website.
  • Forgery: The internet has no memory, when we visit a website, it stores information (cookies) in our browser to identify us. Attackers exploit this functionality by creating an HTTP request that uses this cookie without the user’s knowledge or consent. For example, an attacker can use a hidden form, an image, or a script to forge a request that looks as though it came from the user but carries out the attacker’s malicious intention.

CSRF Attacks in the Real World

We now know that a CSRF attack can make a user perform unwanted actions on a website without their knowledge or consent by using another website or domain to send forged requests. But why should you be concerned?

Anyone who uses the web should be concerned about CSRF attacks, because:

  • It affects a very significant number of websites and users across the web.
  • They are hard to detect as they rely on the user’s browser and cookies to send forged requests.
  • They are easy to execute and exploit, as they only require a user to visit a malicious website or click on a link, or an image.

Here is an example of a CSRF attack that you might encounter in the real world.

Let’s assume you receive an email, a QR code, or an instant message from a friend that invites you to take a fun quiz on a website. The quiz claims to tell you what celebrity you look like the most based on your photo. You are curious and click on the link or scan the code, which takes you to a malicious website. You see a form that asks you to upload your photo and enter your name and email address. You fill out the form and submit it, hoping to see your celebrity match.

However, what you don’t know is that the malicious website also sends another request to your social media account in the background, using your browser’s cookies or session data. If you are already logged into your account this request can perform various actions on your behalf, such as:

  • Posting a message on your timeline or profile that promotes the quiz website and asks all your friends to check it out too.
  • Sending a direct message to your friends that ask them to lend you some money urgently, pretending that you are in trouble.
  • Changing your password, email, or security settings, locking you out of your account.
  • Deleting your posts, photos, or friends, damaging your reputation or relationships.
  • Vote on, comment on, or rate a website on your behalf, influencing the results or opinions of others.

These actions can have serious consequences for you and your friends, such as compromising your privacy, security, or finances. You may not even notice that these actions have taken place until it is too late.

We have written more about CSRF in the past – read our in-depth report on how hackers exploited the UpdraftPlus Plugin, or listen to our Patchstack Weekly security update that dives deep in CSRF vulnerabilities.

How to Prevent CSRF Attacks

CSRF prevention is based on the idea of verifying both the origin and the intention of a request before executing it. Let’s look at the various ways to achieve this.

Validating the Request Headers

The origin and the referer headers are parts of an HTTP request that tell a website where the request came from. A website can use these headers to check if the request was made either by the same website or by a different website. If the request was made by a different website, it could be a CSRF attack and should therefore not be executed.

CSRF Attacks

Your browser sends a referer header when initiating a request. You can check this easily by opening the network section of your browser devtools. In the above example, the value of the referrer header is https://patchstack.com/wordpress-security/.

Using Anti-CSRF Tokens (Nonce)

A nonce is short for numbers used once, but they are not used once. These are random and unique values that are generated and attached to each request. Each token typically lasts for 12 to 24 hours.

By using anti-CSRF tokens, a website can ensure that a request is authorized by the user and not forged by another website. You can create and use nonces in WordPress using two functions:

  • The wp_create_nonce() function creates a nonce value based on a string that you pass as an argument. This string is the name of the nonce, and it should be unique for each action or endpoint that you want to protect. It returns a string that is the value of the nonce.
  • The wp_verify_nonce() function verifies a nonce value that you receive from the browser or another source. You need to pass two arguments to this function: the nonce value and the name of the nonce that you used to create it. It returns “true” if the nonce is valid and “false” if it is not.

You can use nonces to protect your site from CSRF attacks by adding them to any of your forms or requests that perform high-privileged actions. Then, you can check them in your endpoints or functions that process those actions. By doing this, you can ensure that only authorized and legitimate requests are executed.

How to Use a Nonce to Prevent CSRF

There are different methods to implement anti-CSRF tokens, such as:

  • Hidden form fields: This method involves adding a hidden input element to each form that contains the anti-CSRF token value. The token value is generated on the server side and then sent to the browser along with the form. When the user submits the form, the token value is sent back to the server, where it is verified before executing the request.
  • Cookies: This method involves storing the anti-CSRF token value in a cookie on the browser. The cookie is set by the server when the user visits the website or logs in. When the user makes a request, the cookie is sent along with the request, which it is verified by the server before executing the request.
  • HTTP Headers: This method involves sending the anti-CSRF token value in a custom HTTP header. The header is set by a script on the browser when the user makes a request. The script can get the token value from a hidden field, a cookie, or a meta tag. When the server receives the request, it checks the header for the token value and verifies it before executing the request.

These are some of the different techniques that can be used to implement anti-CSRF tokens. Many popular libraries and web frameworks have developed their solutions to prevent CSRF. We recommend you read “How to Use Django’s CSRF Protection Functionality”, and “How the Laravel Framework Handles CSRF Protection”.

By Using SameSite Cookies

This is an attribute that you can add to your cookies to control how they are sent with cross-site requests. SameSite cookies can help prevent CSRF attacks by limiting the scenarios where cookies are sent with requests.

For example, you can use SameSite cookies to only send cookies with requests that originate from your own website or domain, and not send cookies with requests that originate from other websites or domains.

Using Third-Party Solutions

CSRF attacks should be protected at the application level, and it’s difficult to do this from a coarse-grained solution such as an external WAF. But some rules, strategies, and policies can help to mitigate this kind of exploitation, reducing the list of attempts to be controlled in the application.

In addition to cross-site forgery, a WAF can protect your web application from many other common web attacks, such as cross-site scripting, file inclusion, and SQL injection. If you wish to go down this route, you can use the WAF solution by Cloudflare or Sucuri to get started.

Final Thoughts

Cybеrsеcurity, еspеcially when dealing with CSRF attacks, isn’t just a concern – it’s a necessity. CSRF attacks, snеakily making a usеr pеrform unwantеd actions, arе clеvеr, damaging, and surprisingly common.

The spotlight in this article has bееn on their workings and potential prevention methods, such as using anti-CSRF tokens and validating request headers, which create a robust line of dеfеnsе for online entities.

But, let’s not stop our cybersecurity journey hеrе. Exploring further into othеr cybеr thrеats such as XSS and SQL Injеction is crucial in today’s digital agе. Thе kеy takeaway: staying еducatеd and alеrt is our bеst bеt in safеguarding our digital rеalms.

This is also why we built Patchstack

Automated web application protection for site owners, developers, and agencies. 

Most people working with WordPress either: 

  1. Passively worry about their site (and whether they’re taking precautions)
  2. Don’t worry and take little precautions (and are the most at risk)
  3. Spend more time than they should manually secure their sites (often enterprise companies that do code reviews all manually)

Fortunately – thanks to Patchstack, you don’t have to be with: 

  • Notifications for new security vulnerabilities 
  • Automated protection with vPatches and security hardening
  • Remotely managed software and updates with automation

And much, much more. 

For more on WordPress security, read our complete guide to WordPress security here.

We hope you’ve found this tutorial helpful – if you have any questions for us, feel free to reach out to us on our social media platforms. We’re here to help. 🤝

The latest in Security Advice

Looks like your browser is blocking our support chat widget. Turn off adblockers and reload the page.