PHP Token validation rules

Source: Internet
Author: User
Tags vars csrf attack

How PHP adds token validation to the controller

//获得token      private function getToken(){          $tokenName = C( ‘TOKEN_NAME‘ ,null, ‘__hash__‘ );          $tokenType = C( ‘TOKEN_TYPE‘ ,null, ‘md5‘ );          if (!isset( $_SESSION [ $tokenName ])) {              $_SESSION [ $tokenName ]  =  array ();          }          // 标识当前页面唯一性          $tokenKey =  md5( $_SERVER [ ‘REQUEST_URI‘ ]);          if (isset( $_SESSION [ $tokenName ][ $tokenKey ])) { // 相同页面不重复生成session              $tokenValue $_SESSION [ $tokenName ][ $tokenKey ];          } else {              $tokenValue is_callable ( $tokenType ) ?  $tokenType (microtime(true)) : md5(microtime(true));                          $_SESSION [ $tokenName ][ $tokenKey ]   =   $tokenValue ;              if (IS_AJAX && C( ‘TOKEN_RESET‘ ,null,true))                  header( $tokenName . ‘: ‘ . $tokenKey . ‘_‘ . $tokenValue );  //ajax需要获得这个header并替换页面中meta中的token值          }          return array ( $tokenName , $tokenKey , $tokenValue );       }

PHP Forms Add token validation to prevent off-site commit/Repeat commit/double-click Commit


<?php@Session_Start();if($_post) {if($_post[' Privatetoken '] = = $_session[' token ']) {unset($_session[' token ']);Echo' lawful submission '; }Else{Echo' Novalite '; }} $token =MD5(Getrandcode ()); $_session[' token '] = $token;functionGetrandcode () {$str =Array(1,2,3,4,5,6,7,8,9,' A ',' B ',' C ',' d ',' E ',' F ',' G ',' h '); $res ="'; for($i =0; $i <4; $i + +) {$rand =Mt_rand(1,16);    $res. = $str [$rand]; }return$res;}?><!doctypeHTML><HTMLlang="en"><Head> <Metacharset="UTF-8"> <title>form</title></Head><Body><formaction="form.php" method="POST"> url:<inputtype="Text"name="Urlist"/> <inputtype="Hidden"name="Privatetoken"value="<?php Echo$token;?>" /> <BR/> <inputtype="Submit"value="Tijiao"/></form></Body></HTML>-------------------------------------------form is simulated, the session is not regenerated-session
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.
[PHP]View PlainCopyprint?
  1. <?php
  2. /*
  3. * PHP easy to use token to prevent the form of repeated submissions
  4. * This processing method is purely for beginners ' reference
  5. */
  6. Session_Start ();
  7. function Set_token () {
  8. $_session[' token '] = MD5 (Microtime (true));
  9. }
  10. function Valid_token () {
  11. $return = $_request[' token '] = = = $_session[' token ']? True:false;
  12. Set_token ();
  13. return $return;
  14. }
  15. Generates a token if token is empty
  16. if (!isset ($_session[' token ')) | | $_session[' token ']==') {
  17. Set_token ();
  18. }
  19. if (Isset ($_post[' test ')) {
  20. if (!valid_token ()) {
  21. echo "token error";
  22. }else{
  23. Echo ' successfully submitted, Value: '.   $_post[' test '];
  24. }
  25. }
  26. ?>
  27. <form method="POST" action= "" >
  28. <input type="hidden" name="token" value="<?php echo $_session[' token ']?>" >
  29. <input type="text" name="test" value="Default" >
  30. <input type="Submit" value="Submission"/>
  31. </form>

PHP Token validation rules

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.