Cross-site request forgery (CSRF or XSRF) is also known as "Sea Surf" or "Session Riding". But unlike real surfing, it's got nothing to do with waves, water or the beach.
The past 2 weeks I wrote about Cross-Site Scripting. CSRF is similar in nature.
CSRF uses malicious code to send a forged request from the user's browser to a web application. The user is authenticated at the time of the attack, so the forged attack looks exactly the same as a real request.
The consequences
Successful CSRF attacks can have devastating consequences. CSRF attacks can compromise anything that the user can access. This could be:
- Personal data such as email addresses or passwords.
- Data or code that the user can legitimately access.
How does it work?
CSRF requires 3 conditions:
- There must be some action that the attacker wants to execute. It could be specific to the user, like changing the password. Or it could be something that the user has rights to do, like accessing other people's data.
- The action must use cookie-based session handling. The application must rely only on session cookies to verify the user.
- The request parameters needed for the action must be predictable. The attacker can then work out what to use.
A CSRF attack is a two-step approach:
- First it must trick the user into clicking a link or visiting a site that contains the malicious code. This is often done through social engineering - like comments on websites - or emails.
- Then the malicious code sends a forged request from the user's browser to the server. The forged attack looks exactly the same as a legitimate request.
Prevention with CSRF tokens
The most popular way to prevent CSRF is with a challenge token.
CSRF tokens are unique, unpredictable values that are randomly generated for each user session. They are not sent using cookies, but are added through hidden fields or headers. That prevents the attacker from forging a valid request.
Many frameworks have built-in CSRF protection. These frameworks generate CSRF tokens on the server-side to guard against such attacks.
Unfortunately, incorrect validation of CSRF tokens can create more vulnerabilities. So check what your framework provides, and make sure you have configured it correctly.
Read the Portswigger article on CSRF about potential mistakes with CSRF tokens.