利用场景:后台存在添加管理员的功能,如下:
进行抓包观察,发现成功抓包
那么为了防止类似的CSRF攻击的话,肯定需要进行防御措施:
1、验证请求是否token合法
2、判断请求的来源是否合法
token验证:
<script type="text/javascript">
function login() {
var token = "{$token}"
$.post("/index.php?m=index&a=add", {
username: $("#username").val(),
password: $("#password").val(),
token: token,
}, function (data) {
if (data.status == 1) {
window.location.href = data.data.url
} else {
alert(data.msg)
}
}, 'json');
}
</script>
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$token = isset($_POST['token']) ? $_POST['token'] : '';
if(empty($username)) {$this->json(['status'=>0,'msg'=>'账户不能为空!']);unset($_SESSION['token']);}
if(empty($password)) {$this->json(['status'=>0,'msg'=>'密码不能为空!']);unset($_SESSION['token']);}
if(empty($token)) {$this->json(['status'=>0,'msg'=>'token异常!']);unset($_SESSION['token']);}
if($token != $_SESSION['token']){
$this->json(['status'=>0,'msg'=>'token异常!']);
}
//防止token重用需要进行删除
unset($_SESSION['token']);
重新进行抓包,如下,发现添加成功
如果删除token的话再次测试,添加失败
判断请求的来源是否合法: $_SERVER["HTTP_REFERER"]
实现代码:
$referer = $_SERVER["HTTP_REFERER"];
if(!preg_match('~http://smarty.com/.*~',$referer,$a)){
unset($_SESSION['token']);
$this->json(['status'=>0,'msg'=>'非法请求']);
}
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$token = isset($_POST['token']) ? $_POST['token'] : '';
if(empty($username)) {$this->json(['status'=>0,'msg'=>'账户不能为空!']);unset($_SESSION['token']);}
if(empty($password)) {$this->json(['status'=>0,'msg'=>'密码不能为空!']);unset($_SESSION['token']);}
if(empty($token)) {$this->json(['status'=>0,'msg'=>'token异常!']);unset($_SESSION['token']);}
if($token != $_SESSION['token']){
unset($_SESSION['token']);
$this->json(['status'=>0,'msg'=>'token异常!']);
}
//防止token重用需要进行删除
unset($_SESSION['token']);