Home > Article > Backend Development > PHP prevents forged cross-site request implementation program_PHP tutorial
CSRF off-site type vulnerabilities are actually problems with externally submitted data in the traditional sense. Generally, programmers will consider adding watermarks to some forms such as leaving messages and comments to prevent SPAM problems. However, for the sake of user experience, some operations may There are no restrictions, so the attacker can predict the request parameters first, write javascript scripts in the web page outside the site to forge file requests or automatically submit forms to implement GET and POST requests, and the user clicks the link to access in the session state. For web pages outside the site, the client is forced to initiate a request.
Browser security flaws
Almost all current web applications use cookies to identify users and save session status. However, all browsers did not consider security factors when they initially added the cookie function. File requests generated from WEB pages will carry COOKIE. As shown in the figure below, a request generated by a normal picture in the web page will also bring COOKIE:
GET http://website.com/log.jpg
Cookie: session_id
Client ——————————————————-Server
We follow this idea and copy the implementation of crumb. The code is as follows:
The code is as follows | Copy code |
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; } } |
$uid in the code represents the user’s unique identifier, and $ttl represents the validity time of this random string.
Application examples
Insert a hidden random string crumb into the form
The code is as follows
| Copy code
|
||||
Check crumb