Php prevents cross-site request forgery. CSRF vulnerabilities outside the site are actually external data submission issues in the traditional sense. generally, programmers will consider adding watermarks to some forms such as comments to prevent SPAM problems, however, for CSRF off-site vulnerabilities, they are actually external data submissions in the traditional sense. generally, programmers will consider adding watermarks to some forms such as comments to prevent SPAM problems, however, for the sake of user experience, some operations may not be subject to any restrictions. Therefore, attackers can predict the request parameters first, on the off-site Web page, write javascript scripts to forge file requests or automatically submit forms to implement GET and POST requests. in the session state, the user clicks the link to access the off-site Web page, the client is forced to initiate a request.
Browser security defects
Currently, almost all Web applications use cookies to identify users and save session statuses. However, when the Cookie function was initially added to all browsers, the security factor was not taken into account, all file requests generated from the WEB page carry cookies, as shown in. requests generated by a normal image on the Web page also carry cookies:
GET http://website.com/log.jpg
Cookie: session_id
Client ------------------- server
We follow this idea to implement a crumb. the code is as follows:
The code is as follows: |
|
Class Crumb { Const salt = "your-secret-salt "; Static $ ttl = 7200; Static public function challenge ($ data ){ Return hash_hmac ('md5', $ data, self: SALT ); } Static public function issueCrumb ($ uid, $ action =-1 ){ $ I = ceil (time ()/self: $ ttl ); Return substr (self: challenge ($ I. $ action. $ uid),-12, 10 ); } Static public function verifyCrumb ($ uid, $ crumb, $ action =-1 ){ $ I = ceil (time ()/self: $ ttl ); If (substr (self: challenge ($ I. $ action. $ uid),-12, 10) = $ crumb | Substr (self: challenge ($ I-1). $ action. $ uid),-12, 10) ==$ crumb) Return true; Return false; } } |
In the code, $ uid indicates the unique identifier of the user, and $ ttl indicates the validity period of the random string.
Application example
Insert a hidden random string crumb into the form.
Process form demo. php
Check crumb
The code is as follows: |
|
If (Crumb: verifyCrumb ($ uid, $ _ POST ['Crumb']) { // Process the form according to the normal process } Else { // Crumb verification failed, error prompt process } |
Note:
CSRF attacks and the outbreak of related web worms, and develop effective emergency measures for such web attacks. Similarly, it is recommended that programmers do not abuse the $ _ REQUEST variable and add watermarks to some sensitive operations as necessary. in consideration of using formhash technology similar to the DISCUZ forum to increase the difficulty of hacker prediction REQUEST parameters, pay attention to JSON data interface security issues, etc.
...