Подделка межсайтовых запросов (CSRF)

Cross-site request forgery or CSRF, is a kind of vulnerability in web applications that gives an attacker the ability to act as a user and perform unauthorized actions. This can happen if an attacker manages to fool a user who has been authenticated into a web application into sending a request to the application on the attacker’s behalf
Add another way, this kind of attack compels a user to perform out unwanted actions on a website where they are currently authenticated. Through the use of social engineering techniques, such as sending links through chat or email, an attacker can deceive users of a web application into doing actions that they choose. A successful cross-site request forgery (CSRF) attack has the ability to compel a typical user perform state-changing actions, such as transferring money or changing their email address. CSRF has the ability to compromise the entire web application if the victim is an administrative account.
According to the scope of the action, a successful cross-site request forgery (CSRF) attack can grant the attacker total control over the user’s account. If the compromised user has an administrative role within the application, the attacker might have total control over all of the data and features.
Scenario how CSRF works
1. User authentication: A session cookie is sent to the user when they log into a web application.
2. Creating the Malicious Request: The attacker creates a request by placing it in an email, a malicious link, or a third-party website that causes the application to execute an unwanted action.
3. User Interaction: Without realizing of the malicious content, the victim interacts with it after getting authentication.
4. Malicious Request Execution: Thinking it to have been a valid request from the authenticated user, the application uses the user’s credentials to execute the malicious request.
Example: credentials change (email) and cookie session capture
In this example, to understand the concept of CSRF, we will play two roles
the role of victim and attacker
The attacker’s goal – is to replace the victim’s user email with his own and also to get a cookie session id
In the role of the victim, we log into the site not realizing that this site is malicious and we’re being watched.

In the role of the attacker we capture the Cookie session with the help of the Bupr suite, namely HTML request
Cookie: session=6bvQlk6FEbLCrpoxWiYmJdg2PIZSN811

After the victim clicks on the fake link, in the role of the attacker we need to make some HTML request that will trigger the selected request (minus the cookies that will be added automatically by the victim’s browser).
To avoid writing HTML request manually we can use CSRF PoC generator in Buprsuite

We see that the field with the cookie session matches, so we are on the right track, at the end of the request we see the column “email” where the attacker changes to his email [email protected].
Then the attacker generates a request with the substituted data using the previously captured cookies.
Now the attacker has to send this request to the victim’s browser.

But when we send an HTML request to our browser with cookies attached, it tells the server that “it’s me” and I would like to change my email address.
This means that the address change will not happen automatically and the browser will ask the victim if you confirm the request.

The attacker is not interested in giving the victim a choice.
Therefore, the attacker needs it to happen automatically.
To do this, the attacker needs a script that the browser will accept immediately using Javascript
Atacker changed payload of malisios website
To immediately send this form

So the attacker used a script that automatically spoofed the victim’s identity.
as we can see in the last screenshot.

Methodology on testing for vulnerabilities and Checklist
1. Identify State-Changing Operations
Form Submissions: Keep an eye out for any forms that send in information, like those for changing passwords, creating content, or user settings.
AJAX Requests: Recognize requests that are based on AJAX and that send or modify data to the server.
API Endpoints: Verify the API endpoints that the program uses to modify its state.
2. Analyze Session Management
Session Cookies: Check to see if the application is using session cookies for sensitive operations.
Token Usage: Verify if the program use any other cross-site request protection techniques, such as anti-CSRF tokens.
3. Check for Anti-CSRF Tokens
Token Presence: Verify that each state-changing operation needs a distinct anti-CSRF token.
Check that the server correctly validates these tokens and refuses requests that don’t have a valid token.
4. Test Token Implementation
Verify the uniqueness of tokens for each user session and request, if at all possible.
Determine the predictability of a token by evaluating its complexity and making sure it cannot be readily anticipated or circumvented.
5. Examine CORS Policies
Headers for CORS: Examine the Access-Control-Allow-Origin headers to make sure that no requests are being accepted from random domains.
Pre-flight Instructions: Verify that CORS pre-flight requests are managed and limited appropriately.
6. Assess Use of SameSite Cookie Attribute
SameSite Strict Mode: If at all possible, confirm that cookies used for session management or authentication are set to SameSite=Strict.
SameSite Lax Mode: Make sure cookies are set to SameSite=Lax if they must be sent in a top-level navigation.
7. Evaluate User Interaction Requirements
User Actions: Assess if sensitive actions, such as pressing a button, must be initiated by the user directly as opposed to being initiated automatically.
8. Test for Misconfigurations
Misconfigured Headers: Search for missing or incorrectly configured security headers, as these could allow CSRF attacks.
Make sure that cookies have the Secure and HttpOnly flags set in order to block access from client-side scripts.
9. Conduct Manual Testing
Creating Test Requests by Hand: To test how well an application handles unexpected requests from different origins, manually create HTML forms or scripts to mimic cross-site requests.
To check if an application enforces token validation, use the browser developer tools to change requests and add, remove, or modify tokens.
10. Use Automated Scanning Tools
CSRF Testing Tools: Use automated scanners and tools that test different payloads and scenarios in order to find CSRF vulnerabilities.
11. Review Code for Logic Flaws
Analyze the code thoroughly to find any logical errors that could be used as a CSRF exploit. This is especially important for logic related to custom session management and token generation.
12. Document and Report Findings
Exposure Documentation: Make sure to properly record any CSRF vulnerabilities that are discovered, along with the impacted endpoints, the lack of anti-CSRF protection, and any possible consequences.
Reduced Suggested actions: Give thorough advice on how to mitigate the vulnerabilities that have been found, including enhancing CORS regulations, employing SameSite cookie properties, and deploying anti-CSRF tokens.
Scanners and tools:
Manual scanners:
1. Burp Suite
A thorough web security testing tool that enables web applications to be manually tested. It is perfect for testing CSRF vulnerabilities by tampering with request parameters and headers to check for the presence of or weaknesses in anti-CSRF tokens. It has a proxy server to intercept and alter HTTP(S) requests and responses.
Application of CSRF: To determine whether the application processes the request, indicating a vulnerability, use the Repeater and Intruder tools to modify requests and remove or alter CSRF tokens.
2. OWASP ZAP
Web application security scanner that is open-source. It has tools for manual testing requests and responses, such as a repeater and an intercepting proxy.
Application of CSRF: Use it to intercept requests, change the values of CSRF tokens, or remove them altogether. Then, see if the application accepts the modified requests as a way to test for CSRF.
3. WebScarab
Methodology for analyzing programs that use the HTTP and HTTPS protocols for communication. It is helpful for comprehending the inner workings of a web application.
Application of CSRF: You can test how the application reacts to requests that should require a valid CSRF token, without one, or with an invalid one, by intercepting and manipulating HTTP/HTTPS data.
4. Web Developer Toolbar
An add-on for Chrome and Firefox that gives users access to additional web developer tools, such as the capacity to edit requests and forms.
Application of CSRF: You can use it to change or remove CSRF tokens from forms and check if the application enforces token validation.
5. Tamper Data / Tamper Chrome
Browser extensions that let you view and change HTTP/HTTPS headers and post parameters are Tamper Data for Firefox and Tamper Chrome for Chrome.
Use of CSRF: You can use them to test the application’s response to requests to add, remove, or modify CSRF tokens in real time.
6. Postman
A tool for API testing, but it can also be used effectively to test web applications for CSRF vulnerabilities by crafting custom requests.
Usage for CSRF: Create and send custom requests to the application, omitting or altering the CSRF token to test if the application properly checks for the token.
7. Curl / HTTPie
Tools that work with a command line to transfer data via different network protocols. These are especially helpful for web application manual testing.
Create and submit commands to test server-side enforcement by getting around client-side restrictions and skipping CSRF tokens.
Manual Testing Process:
Intercept Requests: To intercept and examine requests sent by the web application, use a proxy program such as Burp Suite or OWASP ZAP.
Find State-Changing Requests: Search for requests that carry out operations such as uploading content, altering user preferences, or carrying out other state changes.
Modify Requests: If there are any CSRF tokens available, use the tools to change or remove them.
Evaluate Reactions: Send in the updated requests, then watch how the application responds to see if it handles the requests without legitimate CSRF tokens, which would suggest a vulnerability.
Automated scanners:
1. Acunetix
Completely automated web vulnerability scanner that searches for and identifies a wide range of vulnerabilities, such as CSRF, XSS, and SQL Injection.
CSRF Detection: Acunetix looks for forms and requests that aren’t accompanied by unique tokens or other mitigations in order to automatically test for CSRF vulnerabilities. It then provides comprehensive reports on findings.
2. Netsparker
Accuracy-focused web application security scanner. It is capable of identifying a number of vulnerabilities, such as SQL Injection, XSS, and CSRF.
As part of its scanning process, Netsparker detects if a web application has any weak or absent anti-CSRF mechanisms.
3. Qualys Web Application Scanning (WAS)
Cloud service that offers automated testing and crawling of unique web apps to find security holes.
By examining online applications for forms and state-changing requests that do not have the necessary anti-CSRF defenses, Qualys WAS is able to detect CSRF vulnerabilities.
4. IBM Security AppScan
Offers web application scanning services that are automated and capable of finding a variety of application vulnerabilities.
AppScan checks web applications for CSRF vulnerabilities, missing tokens, and other anti-CSRF safeguards.
5. Fortify WebInspect
An automated dynamic analysis tool for complex web applications and services is called a dynamic security application testing (DAST) tool.
WebInspect dynamically executes and examines web applications to look for missing anti-CSRF tokens and other potential vulnerabilities. This allows it to scan for vulnerabilities, including CSRF.
6. CSRF Tester
This specialized tool, as its name implies, is only concerned with locating CSRF vulnerabilities.
It gives insights into potential vulnerabilities and automates the testing process.
7. Bright
Bright is a DAST (dynamic application security testing) tool that finds cross-site scripting (CSRF) vulnerabilities.
It helps find possible security flaws in your web apps and offers automated testing capabilities.
Features of Automated CSRF Scanners:
Thorough Scanning: They can swiftly go through a lot of pages and endpoints.
Heuristic Analysis: To find patterns suggestive of CSRF vulnerabilities, many employ heuristic techniques.
Отчетность: They offer thorough reports that identify possible weaknesses, frequently along with recommendations for fixing the issue and a severity rating.
Интеграция: For continuous security testing, many can be incorporated into CI/CD pipelines.
CWE-352: Подделка межсайтовых запросов (CSRF)
is the name given to vulnerabilities involving Cross-Site Request Forgery in the Common Weakness Enumeration (CWE) framework. A thorough, common vocabulary for describing software security issues is provided by the CWE category system for flaws and vulnerabilities in software.
CWE-352 details
In cross-site request forgery (CSRF) attacks, an attacker uses coercion to force a victim’s browser to send a request to a web application that is vulnerable and then executes an unwanted action on the user’s behalf. These attacks basically use the user’s already authenticated session to perform actions without the user’s consent by taking advantage of the trust that a web application has in the user’s browser.
Consequences: Depending on the kind of actions that can be taken with the victim’s credentials, CSRF vulnerabilities may have a substantial impact. Unauthorized modifications to user settings, the user’s posting of undesirable content, unapproved financial transactions, and other malevolent acts that the authenticated user is permitted to carry out are just a few examples of the consequences.
Required conditions:
1. The intended online application needs to have actions that cause side effects and don’t need extra user authentication.
2. At the moment of the attack, the victim needs to be authenticated to the target web application.
3. The request’s structure must be known to the attacker in order for them to carry out the malicious action.
Conclusion of CWE-352:
To improve the security and integrity of software systems, developers, security experts, and software vendors must comprehend CWE-352 in order to recognize, address, and prevent CSRF vulnerabilities in web applications.
Common Vulnerabilities and Exposures (CVE)
These CVEs show how different platforms, frameworks, and applications are affected by CSRF vulnerabilities in different ways. To safeguard their systems and apps, developers and administrators must keep up with these vulnerabilities and quickly implement any required patches or mitigation techniques.
1. CVE-2018-5743
This vulnerability referred to BIND, a popular DNS (Domain Name System) program. It had to do with the web-based control interface, which might have let a CSRF attack change administrative settings or DNS records without the right permission.
2. CVE-2018-0171
A remote attacker could use a CSRF attack to execute arbitrary commands on the device’s operating system with elevated privileges thanks to a vulnerability discovered in the Cisco Smart Install Client.
3. CVE-2016-4978
It was discovered that Apache Struts 2, a well-liked framework for creating Java web applications, was susceptible to a cross-site request forgery (CSRF) attack, which could enable attackers to carry out malicious operations by deceiving an authenticated user into sending a specially crafted request.
4. CVE-2019-0230
The CGI Servlet in Apache Tomcat was found to have a CSRF vulnerability that could enable attackers to carry out unauthorized actions on behalf of authorized users.
5. CVE-2015-9284
An attacker may be able to start a cross-site request forgery (CSRF) attack by deceiving a user into authenticating through a specially crafted request due to a vulnerability in the OmniAuth Ruby gem, which is used for Single Sign-On authentication.
6. CVE-2019-11358
This flaw, known as the “jQuery File Upload” vulnerability, affected the popular jQuery plugin and made it possible for attackers to upload or modify files without authorization and conduct CSRF attacks.
7. CVE-2020-8557
This vulnerability was discovered in Kubernetes, where attackers could execute a denial of service (DoS) attack by using up all of the available resources due to a CSRF bug in the kube-controller-manager.
Courses and Books about CSRF
Курсы:
1. OWASP Top 10 Web Application Security Risks
These courses typically address the OWASP Top 10 security risks, which includes cross-site scripting vulnerabilities. Understanding the background, implications, and mitigation techniques of common web vulnerabilities is greatly aided by taking these courses.
2. Web Security: Understanding the Basics
A wide range of web security topics, including CSRF, are covered in these courses. They include real-world examples of weaknesses and defenses and are appropriate for learners ranging from beginners to intermediates.
In-depth training on web application security includes sections on CSRF attacks and countermeasures in this course. Exercises in hacking and patching are part of this practical course.
4. Web Application Penetration Testing
These are more advanced courses that are appropriate for individuals who want to focus on penetration testing. They explain how to test and exploit a variety of vulnerabilities, such as cross-site scripting flaws (CSRF).
Книги:
This thorough guide addresses CSRF among many other web vulnerabilities. It provides thorough explanations of how attacks operate along with helpful advice on vulnerability testing and mitigation.
2. OWASP Top 10 2017: The Ten Most Critical Web Application Security Risks
This guide gives you a good understanding of the main security risks that web applications face, including cross-site request forgery (CSRF), even though it is not just about CSRF. It’s a fantastic place for newcomers to start.
This book covers CSRF as well as XSS, with a particular emphasis on their occasional intersection. It’s helpful in comprehending web applications’ client-side vulnerabilities.
4. “Web Security for Developers: Real Threats, Practical Defense” by Malcolm McDonald
CSRF is one of the many web security vulnerabilities that are explained in this up-to-date guide in an understandable and useful way. Because it is intended for developers, it simplifies and makes complex subjects understandable.
5. “Hacking: The Art of Exploitation” by Jon Erickson
Despite not being particularly CSRF or web security-focused, this book offers a thorough grasp of exploitation, which is helpful for comprehending the fundamental ideas behind CSRF attacks.
Conclsion :
A serious web security flaw called Cross-Site Request Forgery (CSRF) enables attackers to carry out illegal actions on behalf of legitimate users without their knowledge. It takes advantage of the user’s browser’s trust that a web application has, using the user’s login information to carry out unauthorized operations.
Depending on the features that the vulnerable application exposes, cross-site scripting (CSRF) attacks can have serious consequences, ranging from financial fraud to unauthorized changes to user data and settings. CSRF attacks are a real and present threat to web security because they can be launched from a third-party domain and require little cooperation from the victim.
The use of anti-CSRF tokens, which are specific to each session and request, enforcing the SameSite attribute on cookies to limit them to first-party contexts, and demanding re-authentication for sensitive actions are well-known mitigation strategies for cross-site request fraud. The inclusion of CSRF protections in contemporary web frameworks facilitates application security for developers.
But CSRF is still a problem, as evidenced by its continued presence in the OWASP Top 10 and reported vulnerabilities, especially for older systems and apps that might not have been built with these defenses in mind. To find and fix CSRF vulnerabilities, testing, code review, and ongoing education are crucial.
Web developers, security experts, and anybody else involved in building or managing web applications must comprehend CSRF. The risk posed by cross-site scripting fault tolerance (CSRF) and other web-based attacks can be considerably decreased by keeping up with potential vulnerabilities and following best practices for web security.
Другие Услуги
Insomnia Security Scanner
AI-powered web application security scanner by CQR. Automated vulnerability discovery, exploit verification, and detailed reporting for modern applications.
Узнать большеЗащита Инфраструктуры CRYEYE
Аудит безопасности с помощью CryEye обеспечивает информационную безопасность предприятия, защищая всю инфраструктуру.
Узнать большеТестирование на проникновение
Найдите уязвимости во всей инфраструктуре вашего бизнеса раньше, чем это сделают хакеры! В рамках консалтинга по тестированию на проникновение мы подберем методы пентестов.
Узнать большеСоциальная инженерия
Simulate real-world phishing, vishing, and pretexting attacks to measure and improve your team's security awareness and response capabilities.
Узнать большеНагрузочное Тестирование
All kinds of load and performance testing of your system from the CQR online security company.
Узнать большеAI-Powered Vulnerability Assessment
Leverage artificial intelligence to discover, prioritize, and remediate vulnerabilities across your digital assets faster and more accurately than traditional scanners.
Узнать большеCloud Security Audit (AWS / GCP / Azure)
Comprehensive security review of your cloud environments — IAM policies, network controls, data exposure, and misconfigurations across all major cloud platforms.
Узнать большеDevSecOps Integration
Embed security into every stage of your CI/CD pipeline. Automated SAST, DAST, SCA, and secret scanning so vulnerabilities are caught before they reach production.
Узнать большеAPI Security Testing
In-depth testing of REST, GraphQL, and SOAP APIs for authentication flaws, authorization bypasses, injection vulnerabilities, and data leakage risks.
Узнать большеMobile Application Penetration Testing
Manual and automated security testing for iOS and Android applications — reverse engineering, runtime analysis, traffic interception, and backend API assessment.
Узнать большеIoT Security Assessment
Evaluate firmware, communication protocols, cloud backends, and physical interfaces of IoT devices to identify vulnerabilities before attackers do.
Узнать большеBlockchain & Smart Contract Audit
Formal verification and manual code review of smart contracts on Ethereum, Solana, and other chains. Detect reentrancy, overflow, and logic flaws before deployment.
Узнать большеRed Team Operations
Advanced adversary simulation using real attacker TTPs (MITRE ATT&CK) to test your detection, response, and overall security posture under realistic conditions.
Узнать большеThreat Intelligence & Monitoring
Continuous monitoring of threat feeds, dark web, and attacker infrastructure to provide actionable intelligence specific to your organization and industry.
Узнать большеZero Trust Architecture Review
Assess and design your Zero Trust security model — identity verification, micro-segmentation, least-privilege access, and continuous validation controls.
Узнать большеCompliance Consulting (PCI DSS / SOC 2 / GDPR)
Expert guidance to achieve and maintain compliance with major security frameworks. Gap analysis, remediation roadmaps, and audit-readiness support.
Узнать большеDark Web Monitoring
Continuous surveillance of dark web forums, marketplaces, and breach databases for leaked credentials, sensitive data, or mentions of your organization.
Узнать большеPhishing Simulation & Awareness Training
Controlled phishing campaigns combined with interactive security awareness training to build a human firewall across your entire organization.
Узнать большеSupply Chain Security Audit
Assess third-party vendor risks, open-source dependencies, and software supply chain integrity to prevent attacks like SolarWinds and Log4Shell.
Узнать большеContainer & Kubernetes Security
Security review of Docker images, Kubernetes clusters, RBAC policies, network policies, and runtime configurations to harden your container infrastructure.
Узнать большеWeb Application Firewall (WAF) Deployment
Professional WAF setup, rule tuning, and ongoing management to block SQL injection, XSS, CSRF, and other OWASP Top 10 threats in real time.
Узнать большеBug Bounty Program Management
Full lifecycle management of your bug bounty program — scope definition, researcher coordination, triage, validation, and remediation tracking.
Узнать большеOSINT Investigation Services
Open-source intelligence gathering on individuals, organizations, and infrastructure. Ideal for pre-engagement recon, fraud investigation, and competitive analysis.
Узнать большеDigital Forensics & Incident Response
Rapid response to security breaches — evidence collection, malware analysis, attacker timeline reconstruction, and actionable remediation recommendations.
Узнать больше