Introduction to CSRF
Cross-site request forgery, or CSRF, is a type of attack that makes a victim user perform unwanted operations on a target website.
Put simply, CSRF works by redirecting a victim user to the target website, for example with a link, in such a way to make the user execute specific commands on the website.
The victim user, if authenticated on the website (usually with a Session ID), will immediately execute the commands chosen by the attacker.
CSRF attacks are somehow the opposite of XSS attacks:
- In XSS, the attacker manipulates the code from the website to the user.
- In CSRF, the attacker forces the request from the user to the website.
Let's look at an example.
CSRF attack example
As usual, let's start with a simple example.
Suppose you have a website with registered users. The user.php script is the users' profile page, where each user, after a proper authentication, can see and edit its data.
The user authentication is Sessions-based, so users must provide a valid Session ID to access the page.
From this page, the user can submit a form to change its data: the password, the email address and the first name.
Here is the form:
The back-end, when the form is submitted, validates all the request variables and if the "command" value is "submit" (in the above form this value is set in a hidden input) then the user's settings are updated.
Here is the PHP example code (the validation steps are skipped for the sake of readability):
The user.php page may seem secure, because an attacker cannot directly access it or change a registered user's data unless the user's Session ID is stolen.
However, an attacker can create a link like this:
If the attacker can make the victim user click on the link, the user will be redirected to user.php and will immediately send the commands:
- [email protected]
Since the victim user is authenticated thanks to its Session ID, the command succeeds and the user's private data is changed.
The attacker has successfully changed the user's password and email address with new ones.
CSRF attacks are particularly dangerous because of how easy and destructive they can be.
Preventing CSRF vulnerabilities is therefore of primary importance.
In this course chapter you will learn how to do that.
- CSRF attacks force a victim user to execute specific commands on a website where it's authenticated.
- To perform a CSRF attack, the attacker must redirect the victim user to the target website, for example with a link.