search
HomeBackend DevelopmentPHP TutorialPHP security-cross-site request forgery



Cross-site request forgery

Cross-site request forgery (CSRF) is a type of attack method that allows an attacker to send arbitrary HTTP requests through a victim. The victim here is an unwitting accomplice, and all forged requests originate from him, not the attacker. In this way, it is very difficult for you to determine which requests are cross-site request forgery attacks. In fact, if you don't take precautions against cross-site request forgery attacks, your application is likely to be vulnerable.

Take a look at a simple application below that allows users to purchase pens or pencils. The interface contains the following form:

CODE:

<form action="buy.php" method="POST">
  <p>
  Item:
  <select name="item">
    <option name="pen">pen</option>
    <option
name="pencil">pencil</option>
  </select><br />
  Quantity: <input type="text" name="quantity"
/><br />
  <input type="submit" value="Buy" />
  </p>
  </form>


An attacker will first use your application to gather some basic information. For example, the attacker first accesses the form and discovers the two form elements item and quantity. He also knows that the value of item will be a pencil or a pen.

The following buy.php program handles the form submission information:

CODE:

 <?php
 
  session_start();
  $clean = array();
 
  if (isset($_REQUEST[&#39;item&#39;] &&
isset($_REQUEST[&#39;quantity&#39;]))
  {
    /* Filter Input ($_REQUEST[&#39;item&#39;],
$_REQUEST[&#39;quantity&#39;]) */
 
    if (buy_item($clean[&#39;item&#39;],
$clean[&#39;quantity&#39;]))
    {
      echo &#39;<p>Thanks for your
purchase.</p>&#39;;
    }
    else
    {
      echo &#39;<p>There was a problem with your
order.</p>&#39;;
    }
  }
 
  ?>


An attacker will first use this form to observe it Actions. For example, after purchasing a pencil, the attacker knows that a thank you message will appear after the purchase is successful. After noticing this, the attacker will try to see if the same purpose can be achieved by accessing the following URL to submit data using GET:

http://www.php.cn/

If successful, the attacker now has a URL format that can trigger a purchase when visited by a legitimate user. In this case, it is very easy to conduct a cross-site request forgery attack because the attacker only needs to cause the victim to visit the URL.

While there are many ways to launch a cross-site request forgery attack, using embedded resources such as images is the most common. In order to understand how this attack works, it is first necessary to understand how the browser requests these resources.

When you visit http://www.php.cn/ (picture 2-1), your browser will first request the resource identified by this URL. You can see the return content of this request by viewing the source file (HTML) of the page. The Google logo image was found after the browser parsed the returned content. This image is represented by the HTML img tag, and the src attribute of the tag represents the URL of the image. The browser then issues another request for the image. The only difference between the two requests is the URL.

Figure 2-1. Google’s home page

A CSRF attack can use an img tag to leverage this behavior. Consider visiting a web site with the following image identified in the source:

Based on the above principle, cross-site request forgery attacks can be achieved through the img tag. Consider if the visit includes What will happen to the page with the following source code:

  <img  src="/static/imghwm/default1.png"  data-src="http://store.example.org/buy.php?item=pencil&quantity=50"  class="lazy" / alt="PHP security-cross-site request forgery" >


Since the buy.php script uses $_REQUEST instead of $_POST, every user logged in to the store.example.org store will purchase 50 pencils by requesting this URL.

The existence of cross-site request forgery attacks is one of the reasons why $_REQUEST is not recommended.

The complete attack process is shown in Figure 2-2.

Figure 2-2. Cross-site request forgery attack caused by images

When requesting an image, some browsers will change the Accept value of the request header to give the image type a higher priority. Protective measures are needed to prevent this from happening.

  你需要用几个步骤来减轻跨站请求伪造攻击的风险。一般的步骤包括使用POST方式而不是使用GET来提交表单,在处理表单提交时使用$_POST而不是$_REQUEST,同时需要在重要操作时进行验证(越是方便,风险越大,你需要求得方便与风险之间的平衡)。

  任何需要进行操作的表单都要使用POST方式。在RFC 2616(HTTP/1.1传送协议,译注)的9.1.1小节中有一段描述:

  “特别需要指出的是,习惯上GET与HEAD方式不应该用于引发一个操作,而只是用于获取信息。这些方式应该被认为是‘安全’的。客户浏览器应以特殊的方式,如POST,PUT或DELETE方式来使用户意识到正在请求进行的操作可能是不安全的。”

  最重要的一点是你要做到能强制使用你自己的表单进行提交。尽管用户提交的数据看起来象是你表单的提交结果,但如果用户并不是在最近调用的表单,这就比较可疑了。请看下面对前例应用更改后的代码:

CODE:

 

 <?php
 
  session_start();
  $token = md5(uniqid(rand(), TRUE));
  $_SESSION[&#39;token&#39;] = $token;
  $_SESSION[&#39;token_time&#39;] = time();
 
  ?>
 
  <form action="buy.php" method="POST">
  <input type="hidden" name="token"
value="<?php echo $token; ?>" />
  <p>
  Item:
  <select name="item">
    <option name="pen">pen</option>
    <option
name="pencil">pencil</option>
  </select><br />
  Quantity: <input type="text" name="quantity"
/><br />
  <input type="submit" value="Buy" />
  </p>
  </form>


通过这些简单的修改,一个跨站请求伪造攻击就必须包括一个合法的验证码以完全模仿表单提交。由于验证码的保存在用户的session中的,攻击者必须对每个受害者使用不同的验证码。这样就有效的限制了对一个用户的任何攻击,它要求攻击者获取另外一个用户的合法验证码。使用你自己的验证码来伪造另外一个用户的请求是无效的。

 

  该验证码可以简单地通过一个条件表达式来进行检查:

CODE:

 

 <?php
 
  if (isset($_SESSION[&#39;token&#39;]) &&
      $_POST[&#39;token&#39;] == $_SESSION[&#39;token&#39;])
  {
    /* Valid Token */
  }
 
  ?>


你还能对验证码加上一个有效时间限制,如5分钟:

CODE:

 

<?php
 
  $token_age = time() - $_SESSION[&#39;token_time&#39;];
 
  if ($token_age <= 300)
  {
    /* Less than five minutes has passed. */
  }
 
  ?>


通过在你的表单中包括验证码,你事实上已经消除了跨站请求伪造攻击的风险。可以在任何需要执行操作的任何表单中使用这个流程。

  尽管我使用img标签描述了攻击方法,但跨站请求伪造攻击只是一个总称,它是指所有攻击者通过伪造他人的HTTP请求进行攻击的类型。已知的攻击方法同时包括对GET和POST的攻击,所以不要认为只要严格地只使用POST方式就行了。


以上就是PHP安全-跨站请求伪造的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement
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
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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