Introduction to forged cross-site requests
Forged cross-site requests are difficult to prevent and are extremely harmful. Attackers can use this method to play pranks, send spam messages, delete data, etc. Common forms of this attack include:
Forging links to lure users to click, or allowing users to access without their knowledge
Forging forms to lure users to submit. Forms can be hidden, disguised as images or links.
A common and cheap prevention method is to add a random and frequently changing string to all forms that may involve user writing operations, and then check this string when processing the form. If this random string is associated with the current user identity, it will be more troublesome for the attacker to forge requests.
Yahoo’s way to deal with fake cross-site requests is to add a random string called .crumb to the form; Facebook has a similar solution, and its forms often have post_form_id and fb_dtsg.
Implementation of random string code
Let’s follow this idea and copy the implementation of a crumb. The code is as follows:
Copy the code 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;
}
}
$uid in the code represents the user’s unique identifier, and $ttl represents the validity time of this random string.
Application example
Constructing a form
Insert a hidden random string crumb into the form
Copy code The code is as follows:
Process the form demo.php
Check the crumb
Copy the code 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
}
?>
http://www.bkjia.com/PHPjc/324311.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324311.htmlTechArticleIntroduction to forged cross-site requests. Forged cross-site requests are difficult to prevent and are very harmful. Attackers can use this method. Play pranks, send spam messages, delete data, etc. This attack is common...