Precautions against CSRF attacks

Precautions against CSRF attacks

CSRF (Cross-Site Request Forgery) attack is a common web attack, that is, the attacker uses the user's logged-in identity to send malicious requests to the target website without the user's knowledge, thereby achieving the purpose of the attack. This article will introduce the principles of CSRF attacks and common preventive measures to help web developers better protect user information security.

Insert image description here

The principle of CSRF attack

The principle of CSRF attack is relatively simple. The attacker uses the user's logged-in identity to send malicious requests to the target website to achieve the purpose of the attack. Specifically, the attacker will construct a malicious link or form on his or her website, and then induce the user to click on the link or submit the form, thereby triggering a malicious request to be sent to the target website. Since the user has already logged in to the target website, the malicious request will carry the user's identity information. The target website cannot distinguish whether the request is initiated by the user himself or a request forged by the attacker, so it is vulnerable to attack.

Precautions against CSRF attacks

To avoid CSRF attacks, developers need to take some precautions to enhance the security of their web applications. Here are some common CSRF attack prevention measures:

1. Random token

Random token is a common CSRF attack prevention measure, that is, every time a request is sent to the target website, a randomly generated token (Token) must be carried, and the target website will verify the token when processing the request. Validity, reject the request if invalid. An attacker cannot forge a valid token, thus avoiding CSRF attacks.

Here is an example of random token generation and verification code in PHP:

<?php
// 生成随机令牌
function generate_csrf_token()
{
    
    
    $token = bin2hex(random_bytes(32));
    $_SESSION['csrf_token'] = $token;
    return $token;
}

// 校验随机令牌
function verify_csrf_token()
{
    
    
    if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
    
    
        return true;
    }
    return false;
}

// 示例:生成随机令牌
$csrf_token = generate_csrf_token();

// 示例:校验随机令牌
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    
    if (verify_csrf_token()) {
    
    
        // 处理表单数据...
    } else {
    
    
        // 令牌校验失败,拒绝请求
        die("Invalid CSRF token");
    }
}
?>

In the sample code above, we defined a generate_csrf_token()function and a verify_csrf_token()function to generate and verify random tokens. Specifically, we use random_bytes()the function to generate a random byte array and bin2hex()the function to convert it to a hexadecimal string that serves as the token. At the same time, we save the token in the $_SESSION array of PHP for subsequent verification of the token's validity.

When the form is submitted, we can add the token to the form as a hidden field and then verify the validity of the token on the server side. If the token is invalid, the request is rejected.

2. Referer verification

Referer verification is a simple CSRF attack prevention measure, that is, when processing a request, the Referer header information of the request is verified to ensure that the source of the request is legitimate. Since the browser automatically sends the Referer header information, the attacker cannot forge a legitimate Referer, thereby avoiding CSRF attacks.

The following is an example of PHP's Referer verification code:

<?php
// 校验 Referer 头部信息
function verify_referer()
{
    
    
    if (isset($_SERVER['HTTP_REFERER']) && parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST) === $_SERVER['HTTP_HOST']) {
    
    
        return true;
    }
    return false;
}

// 示例:校验 Referer 头部信息
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    
    if (verify_referer()) {
    
    
        // 处理表单数据...
    } else {
    
    
        // Referer 校验失败,拒绝请求
        die("Invalid Referer");
    }
}
?>

In the sample code above, we define a verify_referer()function to verify the Referer header information of the request. Specifically, we use $_SERVER['HTTP_REFERER']the variable to obtain the Referer header information of the request, and use parse_url()the function to parse the information, extract its host name (host) part, and compare it with the host name of the current website. If the two are the same, the request source is considered legitimate, otherwise the request is rejected.

It should be noted that although Referer verification is simple and effective, it also has certain limitations. Some browsers or security software may disable or tamper with the Referer header information, causing verification to fail. Therefore, it is recommended to take various precautions to enhance the security of web applications.

3. SameSite Cookie

SameSite Cookie is a new CSRF attack prevention measure, that is, when setting a cookie, specify the SameSite attribute of the cookie as Strict or Lax to limit the cross-site access of the cookie. Specifically, the SameSite attribute has the following two values:

  • Strict: Only same-site access is allowed, and any cross-site access is prohibited.
  • Lax: Allows a certain degree of cross-site access, such as link jumps, etc., but prohibits cross-site access for some sensitive operations.

By setting the SameSite attribute, you can avoid some common CSRF attacks, such as CSRF using users' cookies to achieve malicious operations, attackers forging requests in links, etc.

The following is a PHP SameSite Cookie setting code example:

<?php
// 设置 SameSite Cookie
session_set_cookie_params([
    'lifetime' => 3600,
    'path' => '/',
    'domain' => '.example.com',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Strict'
]);
session_start();
?>

In the above sample code, we use session_set_cookie_params()the function to set the parameters of the Session Cookie, including the cookie's lifespan, path, domain name, security flag, HttpOnly flag and SameSite attribute. Among them, we set the SameSite property to Strict to prohibit any cross-site access.

It should be noted that the SameSite attribute cannot completely solve CSRF attacks, and there are still some attack scenarios that require other preventive measures. In addition, some older browsers may not support the SameSite attribute, so other precautions need to be combined to enhance the security of the Web application.

Summarize

CSRF attack is a common web attack that can achieve the purpose of attack by using the user's logged-in identity to send malicious requests to the target website. In order to avoid CSRF attacks, developers need to take some preventive measures, such as random tokens, Referer verification, and SameSite Cookies. Several precautions are recommended to enhance the security of web applications.

Guess you like

Origin blog.csdn.net/JasonXu94/article/details/131702392