CSRF Attack Techniques and How to Prevent CSRF
Website security is extremely important for developers. Experienced developers usually have clever ways to secure their projects, but for beginners, this can be a very challenging issue. When it comes to website security, there are many things to discuss, and of course, I cannot cover everything in one article. Therefore, I will create a series called “Website Security for Coders,” where I will address various security issues related to coding.
The first article in this series will be about the CSRF attack technique (Cross-site Request Forgery). First, let’s understand what this attack technique is.
1. What is a CSRF Attack?
To answer this question, I will present it in a reading comprehension format, meaning I will explain it as I understand it, so there may be some mistakes, and I hope you will forgive them and provide feedback so that I can improve this series.
CSRF attack technique, also known as “Cross-site Request Forgery“, means an attack technique that impersonates the original entity. Let me give you an example to make it easier to understand.
Suppose in your system, you have an action that deletes a user with the following URL: domain.com/delete.php?id=12
(Delete user with ID = 12). So, if someone knows this URL, they could hack it, and they would exploit the system’s admin. They would send an email containing one or more image tags (IMG) with the SRC being that URL, and each image would have a different ID. So, if the admin reads that email while logged into the system, they would accidentally delete the users whose IDs are in the SRC of the images. This is a simple example, but in reality, no one would make a program that deletes users and exposes the ID in the URL like this :D. However, sometimes inexperienced developers make this mistake.
There are many other scenarios, but I think you already understand what it is, so let’s move straight to the solutions.
2. How to Prevent CSRF Attacks
To prevent CSRF attacks, we usually divide it into two groups: the developer and the end user.
For the end user:
- Limit logging into the system when talking to strangers through various channels, especially with emails from unknown sources. Always log out when not using the system.
- It is advisable to log in on a private machine and not allow anyone else to use it.
- Regularly change passwords and choose difficult-to-guess ones with special characters. Because many password-cracking software exist (this isn’t directly related to CSRF but is included for completeness).
For the developer:
- Generate automatic and random tokens for each device and browser, and set an expiration time for those tokens.
- Do not use GET requests for actions that affect the database.
- Strictly validate data input from users.
- URLs in the admin panel should be as hard to remember and as obscure as possible.