PHP Forms Prevent duplicate commits (anti-CSRF vulnerability)

Source: Internet
Author: User
Tags php form csrf attack
This article is about PHP forms to prevent duplicate submissions (anti-CSRF vulnerability), has a certain reference value, now share to everyone, the need for friends can refer to

About token

Token, the most important feature of tokens, is randomness, unpredictable. General hackers or software can not guess out.

So, what does token do? What is the principle of it?

Tokens are typically used in two places-preventing forms from repeating commits, anti CSRF attacks (cross-site request forgery).

Both are based on the principle of the session token to achieve. When the client requests the page, the server generates a random number token, puts the token into the session, and then sends the token to the client (typically by constructing the hidden form). The next time the client submits the request, token is submitted to the server side as a single table.

Then, if applied to the "anti CSRF attack", the server side validates the token value and determines if it is equal to the token value in the session, and if it is equal, it can prove that the request is valid, not forged.

However, if you apply to prevent form recurrence, the server side will update the token value in the session after the first validation, and if the user repeats the commit, the second validation judgment will fail because the token in the user's submitted form is unchanged. But token has changed in the server-side session.

The above session application is relatively safe, but also called cumbersome, and when multi-page multi-request, must use multi-token simultaneous generation method, so that the use of more resources, execution efficiency will be reduced. Therefore, cookies can also be used to store authentication information in place of Session tokens. For example, when a "duplicate commit" is submitted, the information that has been submitted is written to the cookie after the first commit, and when the second commit, the second commit fails because the cookie already has a record of its submission.

However, Cookie storage has a fatal weakness, and if a cookie is hijacked (an XSS attack can easily get a user cookie), then again Gameover. Hackers will directly implement CSRF attacks.

1. Prevent XSS attacks first

2. Verify Referrer

3. Important cookies Set HTTPS only, such as token

4. Using signatures, tokens

5.get only for querying information

6. Form submission with Post

7. Use cross-script injection with caution

So, safe and efficient relative. Specific questions to deal with it.


PHP forms Add tokens to prevent duplicate submissions

The principle is to generate a random string to put in the session, submit the form and then verify the string, you can prevent others to write their own form to deceive the submission, repeated submissions or double-click Submit.

The simple code implemented in PHP is as follows:


<? php/** PHP Simple use token to prevent the form of repeated submission * This processing method is purely for beginners reference */session_start (); function Set_token () {$_session[' token '] = MD5 ( Microtime (True));} function Valid_token () {$return = $_request[' token '] = = = $_session[' token ']? True:false; Set_token (); return $return;} Generates a tokenif (!isset ($_session[' token ') "If token is empty) | | $_session[' token ']== ') {Set_token ();} if (isset ($_post[' test ')) {if (!valid_token ()) {echo "token error"; }else{Echo ' successfully submitted, Value: '. $_post[' test '; }}?><form method= "POST" action= "" > <input type= "hidden" name= "token" value= "<?php echo $_session[" Token ']?> ' > <input type= "text" name= "test" value= "Default" > <input type= "Submit" value= "Submit"/></ Form>


The more simple method above, the following code is a little more secure.

token.php


<?php/* * Created on 2013-3-25 * To change the template for this generated file go to * window-preferences-phpecl Ipse-php-code Templates */function getToken ($len = all, $md 5 = True) {# Seed random number generator # only needed F  or PHP versions prior to 4.2 Mt_srand ((double) microtime () * 1000000);     # array of characters, adjust as desired $chars = Array (' Q ', ' @ ', ' 8 ', ' y ', '% ', ' ^ ', ' 5 ', ' Z ', ' (', ' G ', ' _ ', ' O ', ' ', ' S ', '-', ' N ', ' < ', ' D ', ' {', '} ', ' [', '] ', ' H ' , '; ', ' W ', '. ', '/', ' | ', ': ', ' 1 ', ' E ', ' L ', ' 4 ', ' & ', ' 6 ', ' 7 ', ' # ', '    9 ', ' A ', ' a ', ' B ', ' B ', ' ~ ', ' C ', ' d ', ' > ', ' E ', ' 2 ', ' f ', ' P ', ' g ', ') ', '? ', ' H ', ' I ', ' X ', ' U ', ' J ', ' K ', ' r ', ' L ', ' 3 ', ' t ', ' M ', ' n ', ' = ', ' o ', ' + ', ' P ', ' F ', ' Q ', '! ', ' K ', ' R ', ' s ', ' C ', ' m ', ' T ', ' V ', ' j ', ' u ', ' V ', ' w ', ', ', ' X ', ' I ', ' $ ', ' Y ', ' z ', ' * ');  # Array Indice friendly number of chars;  $numChars = count ($chars)-1;  $token = "; # Create Random token at the specified length for ($i = 0; $i < $len; $i + +) $token. = $chars [Mt_rand (0, $numChars)]  ;  # should token be run through MD5?    if ($MD 5) {# Number of 32 char chunks $chunks = Ceil (strlen ($token)/);    $MD 5token = "; # Run each chunk through MD5 for ($i = 1; $i <= $chunks; $i + +) $MD 5token. = MD5 (substr ($token, $i * 32-32, 32    ));  # Trim The token $token = substr ($md 5token, 0, $len); } return $token;}? >


form.php


<?phpinclude_once (" Token.php "); $token = GetToken (); Session_Start (); $_session[' token '] = $token;? ><form action= "action.php" method= "POST" <input type= "hidden" name= "token" value= "<?= $token?>"/> <!--other--></form> such as input submit, 


action.php



<?phpsession_start (); if ($_post[' token '] = = $_session[' token ') {  unset ($_session[' token ']);  echo "This is a normal submission request";} else{  echo "This is an illegal submission request"; >


Related recommendations:

PHP form Name value with variable representation problem

PHP form file iframe Asynchronous upload instance detailed



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.