This course is a hands-on lab tutorial. To explain certain operations in the lab, theoretical content will be included, and carefully selected must-read articles will be recommended. This approach ensures you develop a strong theoretical understanding of concepts like CSRF vulnerability while engaging in practical exercises.
Note: Due to high configuration costs, the cloud server used for experiments is limited to six sessions per experiment.
2. Learning Approach
The Kali series courses on Shiyanlou include five training camps. This particular course focuses on web application attack methods. It offers 20 experiments, each equipped with detailed steps and screenshots. Itâs ideal for those with a basic understanding of Linux who wish to quickly get started with Kali penetration testing.
The key to learning is frequent practice and asking questions. After starting an experiment, follow the steps incrementally while understanding the details of each action.
If the beginning of an experiment includes recommended readings, ensure you review them first. Theoretical knowledge is the essential foundation for practice.
3. Section Overview
In this experiment, we introduce the concepts of Kali Linux and penetration testing. Youâll need to complete the following tasks sequentially:
Introduction to CSRF
Hands-On CSRF Attack
CSRF Prevention
4. Recommended Reading
For this experiment, we recommend reading the following content:
CSRF stands for Cross-Site Request Forgery, often referred to as a âone-click attackâ or âsession riding.â
The essence of this attack lies in its name: âforgery.â It involves forging a request to impersonate user actions.
Attackers use specific techniques to trick a userâs browser into visiting a previously authenticated website and performing operations (like sending emails, posting messages, or even executing financial actions like transferring funds or making purchases). Since the browser was previously authenticated, the website assumes the actions are legitimate and proceeds with them. This exploits a security gap in web user authentication: verifying that a request comes from a userâs browser does not confirm that the user willingly initiated the request. (Source: Wikipedia)
This authentication relies on cookies, which store a value string on both the server and client side. During subsequent requests, this information is sent to the server, allowing it to identify different users. This maintains a logged-in state for users across pages.
To illustrate, when accessing a shopping site, any page visit submits a request that includes the userâs cookie. Consequently, every page reflects that the user is logged in. An attacker can exploit this by tricking the user into clicking a malicious link, which could silently change their password or perform other unauthorized actions.
This attack occurs without stealing any information.
The description above might remind you of reflective XSS attacks. In fact, XSS and CSRF attacks are often confused.
In many cases, CSRF attacks utilize XSS techniques. Such attacks are generally referred to as XSRF. However, CSRF encompasses more exploit methods than just XSS.
Typically, injecting JavaScript code to steal information or trigger pop-ups falls under XSS. For instance, injecting code to redirect users to a different page, pop up a window, steal HTML content, or attack a server.
On the other hand, exploiting a userâs cookie for unauthorized actions unbeknownst to the userâlike changing passwords or transferring fundsâis classified as CSRF.
5.3 CSRF Lab Environment
As with previous experiments, weâll use the DVWA environment. To start, launch the lab environment. If youâre already familiar with this process, you may skip this step.
On the lab desktop, double-click the Xfce terminal to open it:
To start the Metasploitable2 virtual machine, use the command sudo virsh start Metasploitable2:
Wait approximately four minutes for the VM to fully load. Then, open Firefox from the desktop:
Access the IP address of your virtual machine system 192.168.122.102:
After successfully starting the virtual machine system, visiting this IP address should present you with a webpage similar to the one shown.
Click on DVWA to enter its login page. The default username and password are admin and password. Once logged in, youâll see the following interface:
To perform the simplest attack, we will set the security settings to the lowest default level. First, access the security settings adjustment page:
Then, adjust the security level to âlowâ:
Once you see the âLevelâ setting update at the bottom of the page, the modification has been successfully applied:
5.4 CSRF Initial Test
Visit the CSRF testing page provided by DVWA:
In the test environment, you are presented with a password modification scenario. Here, you can simply input a new password and confirm it to change it:
Click the âchangeâ button:
A success message will appear indicating the password has been changed. Close the browser and attempt to log in again:
/wm)
At this point, youâll see a login failed message. However, using the password you just set will successfully log you in, verifying that the password change was successful.
Note: Upon logging back in, the DVWA security level defaults to âhigh.â Youâll need to reset the level again.
Return to the CSRF password modification page to try changing the password again:
Click the change button again and focus on the URL in the address bar:
This example shows code submitted via the GET method, which demonstrates just how insecure the site is. Without further inspection, just from the URL, one could identify the newly updated username and password.
Do not close this page yet. Open a new tab and navigate to the DVWA page again (for example, accessing 192.168.122.102/dvwa). You will observe that logging in again isnât required, which is due to the presence of cookies. But what happens if someone accesses this URL?
Youâll notice the modification happens successfully, even though the user has not manually entered any credentials. The user is completely unaware that their information has been involuntarily altered. Letâs verify if the password has indeed been changed to test_shiyanlou.
Restart the browser (to avoid using the same existing cookies when accessing the DVWA site). Reopen the browser and navigate back to the DVWA page:
Attempt to log in using the password shiyanlou. As expected, the login fails with the message login failed, confirming that the prior modification succeeded. Now, try logging in with test_shiyanlou:
Logging in successfully demonstrates the password was indeed modified. This scenario illustrates the Cross-Site Request Forgery (CSRF) vulnerability. Without stealing a userâs information, attackers exploit trust and cleverly manipulate users into modifying sensitive details through their own authenticated session.
Although this approach may appear too obvious and suspicious for users to click, attackers can disguise malicious actions by crafting deceptive links. For example, an attacker could mask it as a downloadable file or an image. Clicking these traps would trigger the exploit unnoticed.
If cookies are available, you can also use a tool like curl to replicate this exploit locally:
Open the browser developer tools (via F12) and navigate to the Network section to find cookie information. Extract the cookie values:
Then execute the following command in the terminal:
Be sure to use your own cookie values and input your desired new password in the URL. After execution, the response will return the source code of the target page:
Observant users will notice the phrase Password Changed in the returned HTML, which confirms a successful update.
To automate verification of password change success, you can use the following grep command:
To finalize, verify login success by either restarting your browser and logging back in, or by clicking the logout button and attempting to relog.
Another method involves social engineering tactics to exploit CSRF vulnerabilities covertly (inspired by Tipstrickshack Blog):
Create a 404 page using an img tag, but use CSS to hide it. This way, users unknowingly fall for the trap without realizing it.
First, under the terminal of the shiyanlou account, create an HTML file named test:
vim test.html
Then, add the following content to the file:
Welcome to nginx!
You can see that we use two phrasesâ404 and Not Foundâto mislead users. The img tag automatically loads our phishing link but remains invisible. As a result, even if the user falls into the trap, they wonât be aware of what happened.
After saving and exiting, locate the file in the home directory:
Double-click the file to open it in Firefox. Once loaded successfully, return to the DVWA platform. After clicking Logout and attempting to log in again, youâll notice the password has been changed, and login is no longer possible.
This demonstrates a CSRF attack, which exploits cookies to impersonate users and perform actions theyâre unaware of.
5.4 CSRF Prevention
Log in to DVWA again, and check the source code:
In the source code, variables are directly retrieved, and a simple conditional check is performed before encrypting and storing the data in the database.
If the security level is increased to âMedium,â youâll see an additional check in the source code:
if ( eregi ( "127.0.0.1", $_SERVER['HTTP_REFERER'] ) ){
The eregi() function performs case-insensitive regex matching, checking if the first parameter exists in the string specified by the second parameter. However, this function is no longer supported as of PHP 5.3. This code checks if the referring URL contains 127.0.0.1. If the match is successful, the password change is allowed; otherwise, itâs blocked.
This method is flawed, as users may access the platform via an address other than 127.0.0.1. In higher security levels, 127.0.0.1 is replaced with $_SERVER['SERVER_NAME'].
We observed that this conditional check can prevent legitimate password changes if the user isnât using 127.0.0.1 as the access point. This can be bypassed by renaming the test.html file to 127.0.0.1.html:
Since the $_SERVER['HTTP_REFERER'] variable only works with server-side requests, we must host the file on the server. By moving it to /usr/share/nginx/html, which is the root directory for Nginx, and ensuring that service nginx start is active, the file can be accessed via 192.168.122.1/127.0.0.1.html to modify the password.
Note: Be sure to modify the password within 127.0.0.1.html to confirm that the password was successfully changed.
This demonstrates that medium-level security measures are insufficient. When the security level is increased to âHigh,â the CSRF page changes, requiring three parameters for password modification: the new password, its confirmation, and the current password. Without knowing the current password, an attacker cannot silently change it.
This method is straightforward yet effective in preventing such attacks. Additionally, tokens can be added to form submissions for validation, but tokens are ineffective if cookies are compromised. Another method involves using CAPTCHA, ensuring changing passwords isnât as simple as clicking a link.
6. Summary
In this experiment, we learned the following concepts. If you have any questions, feel free to visit the Shiyanlou Q&A forum:
Introduction to CSRF
CSRF in Practice
CSRF Prevention
Make sure you perform the entire experiment yourself. While reading may seem easy, real operations often raise unexpected issues. The process of solving these challenges is where the real learning happens.