Home Backend Development PHP Tutorial PHP implements secure programming: CSRF attack and defense

PHP implements secure programming: CSRF attack and defense

Jun 18, 2023 pm 12:22 PM
php csrf Secure programming

In Internet applications, security issues have always been an important issue. Among them, Cross-Site Request Forgery (CSRF) attack is a common vulnerability and one that is easily exploited by attackers. So, how to implement secure programming in PHP development? This article will focus on CSRF attacks and defense solutions.

1. What is CSRF attack?

CSRF attack, cross-site request forgery, is an attack method that uses the victim's logged-in status to send malicious requests to the target website without the victim's knowledge. An attacker may obtain the victim's login status through various methods, and then initiate a forged request to the target website without being noticed, thereby carrying out the attack. The attacker may induce the victim to perform operations by allowing the victim to visit a third-party website, through links in emails or chat software, or by posting links on social networks, thereby triggering the attack.

In the following example, an attacker can let the victim visit a malicious website, generate a POST request, disguise it as a request from the target website, and obtain the permissions of the victim when he is logged in, that is, submit a comment:

<form action="https://www.targetwebsite.com/comment" method="post">
<input type="hidden" name="comment" value="harmful comment" />
<input type="submit" value="Submit Comment" />
</form>
<script>
document.forms[0].submit();
</script>
Copy after login

This attack method is very subtle, because the attacker does not attack the target website directly, but takes advantage of the vulnerabilities of the target website to achieve the attack. Since the victim is unaware, it is difficult to detect the attack. If the target website fails to prevent CSRF attacks, it may lead to data leakage, malicious operations and other risks.

2. How to defend against CSRF?

Since CSRF attacks are so dangerous, how to defend against them? The following are some common defense strategies:

1. Add token verification

When the user logs in, the backend server generates a token and sends it back to the front end, and saves the token to the server. In subsequent interactions with the server, the front end needs to bring the token to the server along with the request. The server can determine whether the request is legitimate through token verification.

The following is a simple code example:

<!-- 后端代码 -->
<?php
session_start();
if(!isset($_SESSION['token'])){
$_SESSION['token'] = md5(uniqid(rand(), true));
}
$token = $_SESSION['token'];
?>

<!-- 前端代码 -->
<form method="post" action="/some/url">
<?php echo "<input type='hidden' name='token' value='".$token."' />"; ?>
<input type="text" name="username" />
<input type="text" name="password" />
<input type="submit" value="Submit" />
</form>
Copy after login

In this example, we generate a random token in the background and pass it back to the front end. Next, the token is appended to the hidden input tag. When the front end submits a request, the token will also be submitted, and the code on the server will verify whether the request is legal based on the submitted token.

2. Add Referer verification

Referer is part of the HTTP header, which contains the page from which the user redirected to the current page. By checking the Referer in the HTTP header, the server can determine whether the request comes from a legitimate page. If the Referer is detected to be incorrect, the server will refuse to respond to the request.

The following is a simple code example:

<?php
$referer = $_SERVER['HTTP_REFERER'];
if(parse_url($referer, PHP_URL_HOST) != 'www.validwebsite.com') {
die("Invalid Referer");
}
// 处理正常的请求
?>
Copy after login

In this example, we get the Referer in the HTTP header and check if the request comes from a website named "www.validwebsite.com" website. If the request does not come from this website, the server will reject the response and display an "Invalid Referer" message.

3. Add browser cookies

Cookie-based CSRF attack is an attack method that uses the user's login status and sends the user's cookie to the attacker's website. We can do this by setting a short-lived cookie for a sensitive page and then checking for the cookie's existence when performing actions related to that page.

The following is a simple code example:

header('Set-Cookie: csrf_cookie=' . uniqid(rand(), true) . '; path=/; HttpOnly');
Copy after login

In this example, we generated a random csrf_cookie and set it to HttpOnly, which means the cookie can only be passed through the HTTP protocol transfer, and cannot be accessed via JavaScript. When the request reaches the server, we can check if its cookie matches that page, identifying a possible attack.

Summary

CSRF attack is a very dangerous attack method. Defending against CSRF attacks not only helps protect data security, but is also a basic requirement for implementing secure programming. In the PHP development environment, we can take some measures to prevent CSRF attacks, such as setting token verification, Referer verification, adding browser cookies, etc. Through these measures, we can effectively protect user login states and pages involving sensitive data from attacks.

The above is the detailed content of PHP implements secure programming: CSRF attack and defense. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

CakePHP Logging CakePHP Logging Sep 10, 2024 pm 05:26 PM

Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy. The log() function is provide

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

See all articles