search
HomeBackend DevelopmentPHP TutorialCross-site request forgery CSRF attack and defense

1. What is CSRF?

 CSRF (Cross-site request forgery), Chinese name: cross-site request forgery, also known as: one click attack/session riding, abbreviated as: CSRF/XSRF.

2. What can CSRF do?

You can understand CSRF attacks this way: the attacker steals your identity and sends malicious requests in your name. What CSRF can do includes: sending emails and messages in your name, stealing your account, and even purchasing goods, virtual currency transfers... The problems caused include: leakage of personal privacy and property security.

3. Current status of CSRF vulnerabilities

This attack method of CSRF has been proposed by foreign security personnel in 2000, but in China, it did not start to attract attention until 2006. In 2008, many large communities and interactive websites at home and abroad CSRF vulnerabilities were exposed respectively, such as: NYTimes.com (New York Times), Metafilter (a large BLOG website), YouTube and Baidu HI... But now, many sites on the Internet are still unprepared for this, So much so that the security industry calls CSRF the "sleeping giant."

IV. Principle of CSRF

To complete a CSRF attack, the victim must complete two steps in sequence:

 1. Log in to the trusted website A and generate a cookie locally.

 2. Access dangerous website B without logging out of A.

 Seeing this, you may say: "If I do not meet one of the above two conditions, I will not be attacked by CSRF." Yes, it is true, but you cannot guarantee that the following situations will not happen:

  1. You cannot guarantee that after logging into a website, you will no longer open a tab page and visit another website.

  2. You cannot guarantee that after you close the browser, your local cookies will expire immediately and your last session has ended. (In fact, closing the browser cannot end a session, but most people mistakenly believe that closing the browser is equivalent to logging out/ending the session...)

  3. The so-called attack website in the picture above, It could be a trusted, frequently visited website that has other vulnerabilities.

The above briefly talks about the idea of ​​CSRF attacks. Below I will use several examples to explain specific CSRF attacks in detail. Here I use a bank transfer operation as an example (just an example, real bank websites are not so stupid. :>)

 Example 1:

 Bank website A, which uses GET requests to complete bank transfer operations, such as: http://www.mybank.com/Transfer.php?toBankId=11&money=1000

 Dangerous website B, there is a piece of HTML code in it as follows:

 Cross-site request forgery CSRF attack and defense

 First, you log in to bank website A, and then visit dangerous website B. Oh, then you will find that your bank account is missing 1,000 yuan.... ..

 Why is this? The reason is that bank website A violates HTTP specifications and uses GET requests to update resources. Before accessing dangerous website B, you have already logged in to bank website A, and B uses GET to request third-party resources (the third party here refers to the bank website. Originally this was a legal request, but here it was Criminals have taken advantage of it), so your browser will bring the cookie of your bank website A to issue a Get request to obtain the resource "http://www.mybank.com/Transfer.php?toBankId=11&money=1000", As a result, after the bank website server received the request, it thought it was an update resource operation (transfer operation), so it immediately performed the transfer operation...

 Example 2:

 In order to eliminate the above problem, the bank decided to use POST request completes the transfer operation.

The WEB form of bank website A is as follows:

    <form action="Transfer.php" method="POST">
    <p>ToBankId: <input type="text" name="toBankId" /></p>
    <p>Money: <input type="text" name="money" /></p>
    <p><input type="submit" value="Transfer" /></p>
  </form>

The background processing page Transfer.php is as follows:

    <?php
    session_start();
    if (isset($_REQUEST[&#39;toBankId&#39;] && isset($_REQUEST[&#39;money&#39;]))
    {
        buy_stocks($_REQUEST[&#39;toBankId&#39;], $_REQUEST[&#39;money&#39;]);
    }
  ?>

Dangerous website B still only contains the HTML code:

Cross-site request forgery CSRF attack and defense

  和示例1中的操作一样,你首先登录了银行网站A,然后访问危险网站B,结果.....和示例1一样,你再次没了1000块~T_T,这次事故的原因是:银行后台使用了$_REQUEST去获取请求的数据,而$_REQUEST既可以获取GET请求的数据,也可以获取POST请求的数据,这就造成了在后台处理程序无法区分这到底是GET请求的数据还是POST请求的数据。在PHP中,可以使用$_GET和$_POST分别获取GET请求和POST请求的数据。在JAVA中,用于获取请求数据request一样存在不能区分GET请求数据和POST数据的问题。

  示例3:

  经过前面2个惨痛的教训,银行决定把获取请求数据的方法也改了,改用$_POST,只获取POST请求的数据,后台处理页面Transfer.php代码如下:

   <?php
    session_start();
    if (isset($_POST[&#39;toBankId&#39;] && isset($_POST[&#39;money&#39;]))
    {
        buy_stocks($_POST[&#39;toBankId&#39;], $_POST[&#39;money&#39;]);
    }
  ?>

  然而,危险网站B与时俱进,它改了一下代码:

<html>
  <head>
    <script type="text/javascript">
      function steal()
      {
               iframe = document.frames["steal"];
               iframe.document.Submit("transfer");
      }
    </script>
  </head>
  <body onload="steal()">
    <iframe name="steal" display="none">
      <form method="POST" name="transfer" action="http://www.myBank.com/Transfer.php">
        <input type="hidden" name="toBankId" value="11">
        <input type="hidden" name="money" value="1000">
      </form>
    </iframe>
  </body>
</html>

如果用户仍是继续上面的操作,很不幸,结果将会是再次不见1000块......因为这里危险网站B暗地里发送了POST请求到银行!

  总结一下上面3个例子,CSRF主要的攻击模式基本上是以上的3种,其中以第1,2种最为严重,因为触发条件很简单,一个就可以了,而第3种比较麻烦,需要使用JavaScript,所以使用的机会会比前面的少很多,但无论是哪种情况,只要触发了CSRF攻击,后果都有可能很严重。

  理解上面的3种攻击模式,其实可以看出,CSRF攻击是源于WEB的隐式身份验证机制!WEB的身份验证机制虽然可以保证一个请求是来自于某个用户的浏览器,但却无法保证该请求是用户批准发送的!

五.CSRF的防御

CSRF 的防范机制有很多种,防范的方法也根据 CSRF 攻击方式的不断升级而不断演化。常用的有检查 Refer 头部信息,使用一次性令牌,使用验证图片等手段。出于性能的考虑,如果每个请求都加入令牌验证将极大的增加服务器的负担,具体采用那种方法更合理,需要谨慎审视每种保护的优缺点。

1. 检查 HTTP 头部 Refer 信息,这是防止 CSRF 的最简单容易实现的一种手段。根据 RFC 对于 HTTP 协议里面 Refer 的定义,Refer 信息跟随出现在每个 Http 请求头部。Server 端在收到请求之后,可以去检查这个头信息,只接受来自本域的请求而忽略外部域的请求,这样就可以避免了很多风险。当然这种检查方式由于过于简单也有它自身的弱点:

a) 首先是检查 Refer 信息并不能防范来自本域的攻击。在企业业务网站上,经常会有同域的论坛,邮件等形式的 Web 应用程序存在,来自这些地方的 CSRF 攻击所携带的就是本域的 Refer 域信息,因此不能被这种防御手段所阻止。

b) 同样,某些直接发送 HTTP 请求的方式(指非浏览器,比如用后台代码等方法)可以伪造一些 Refer 信息,虽然直接进行头信息伪造的方式属于直接发送请求,很难跟随发送 cookie,但由于目前客户端手段层出不穷,flash,javascript 等大规模使用,从客户端进行 refer 的伪造,尤其是在客户端浏览器安装了越来越多的插件的情况下已经成为可能了。

2. 使用一次性令牌,这是当前 Web 应用程序的设计人员广泛使用的一种方式,方法是对于 Get 请求,在 URL 里面加入一个令牌,对于 Post 请求,在隐藏域中加入一个令牌。这个令牌由 server 端生成,由编程人员控制在客户端发送请求的时候使请求携带本令牌然后在 Server 端进行验证。但在令牌的设计上目前存在着几个错误的方案:

a) 使用和 Session 独立的令牌生成方式。这种令牌的值和 Session 无关,因此容易被其他用户伪造。这里的其他用户指的是当前 Web 应用程序的其他用户和活跃在网络传输阶段各个设置上的监听者,这种恶意用户可能使用自己的令牌来进行替换以便达到伪造的目的。

b) 完全使用 Session 认证信息作为令牌的生成方式。这种保护方式对于保护 CSRF 是起了作用的,但是可能会造成其他危害,具体来说,如果某些 URL 或者网页被拷贝下来与其他人共享,那么这些 URL 或者拷贝下来的网页中可能会含有用户的会话信息,这种信息一旦被恶意用户获得,就能造成极大的危害。

因此,一个正确的令牌设计应该是使用 Session 信息做 Hash,用得出的哈希值来做 CSRF 的令牌。

3. Use verification images. The purpose of this method is to prevent brute force attacks by robots. However, in terms of CSRF prevention, there are also some applications with relatively high security requirements that combine verification pictures and one-time tokens for double protection. Because this image verification information is difficult for malicious programs to identify on the client, it can provide stronger protection. When the client's browser may already be in an unsafe environment (for example, the client's security level is set to a low level, the client's browser has unsafe plug-ins installed, etc.).

The above are just some of the more general methods to prevent CSRF. Web developers can determine the security level requirements based on their understanding of the functions of their applications and choose to use different protection measures. It is also recommended to use them in the same application. A combination of methods are used within the program for protection.

Note: Adding defenses will also greatly affect performance, just like putting a toll station on the highway. It is recommended to only add defenses to important operations. Please consider carefully.


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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

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.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.