Cybersecurity 101 Categories
What is Cross-Site Request Forgery (CSRF) and how does it work?
Cross-Site Request Forgery (CSRF) is a web security vulnerability that tricks an authenticated user into performing unwanted actions on a web application. By exploiting the trust a site has in the user’s browser, an attacker can send unauthorized requests on behalf of the victim without their knowledge.
Here’s how it works:
- The attacker embeds malicious code in a link or script on a page they control or in an email sent to the victim.
- When the victim, who is already logged into the target application, clicks the link or visits the page, the browser automatically includes their session cookie in the request to the target site.
- The web application, seeing a valid session cookie, processes the request as though it came from the authenticated user.
For example, an attacker might send a link that transfers money from the victim’s bank account. If the victim is logged into their online banking, clicking the link will execute the transfer using their authenticated session.
What are the common examples of CSRF attacks?
Common examples of CSRF attacks include:
- Money Transfers: An attacker tricks a user into transferring funds from their bank account to one controlled by the attacker.
- Account Updates: Attackers modify a user’s email address or account password to gain control.
- Changing App Settings: In enterprise systems, CSRF can alter administrative settings like adding new users or changing roles.
- Social Media Actions: CSRF can post unauthorized messages, send friend requests, or follow accounts.
These attacks are particularly dangerous because they leverage authenticated sessions, making them difficult to detect as malicious.
How can developers prevent CSRF attacks in web applications?
Developers can prevent CSRF by implementing the following measures:
- CSRF Tokens: Include unique, unpredictable tokens in requests that modify data. Servers validate these tokens before processing the request.
- SameSite Cookies: Set cookies to
SameSite=Lax
orSameSite=Strict
to prevent them from being sent with cross-origin requests. - User Verification: Require users to re-enter credentials for sensitive actions.
- CORS Policies: Enforce strict Cross-Origin Resource Sharing (CORS) rules.
What is the difference between CSRF and Cross-Site Scripting (XSS)?
CSRF exploits the trust that a web application has in the user’s browser. It uses authenticated sessions to perform unauthorized actions without user consent. Conversely, Cross-Site Scripting (XSS) exploits the trust a user has in a web application by injecting malicious scripts into webpages viewed by other users.
While CSRF focuses on unauthorized actions, XSS primarily targets data theft, session hijacking, or defacing the site.