• CSRF的安全问题


    利用场景:后台存在添加管理员的功能,如下:

    进行抓包观察,发现成功抓包

    那么为了防止类似的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']);
    

  • 相关阅读:
    python unittest单元测试框架-3用例执行顺序、多级目录、装饰器、fixtures
    python unittest单元测试框架-2discover
    python unittest单元测试框架-1
    python selenium-4自动化测试模型
    python selenium-9 grid模式
    20)PHP,数组的遍历
    19)PHP,数组知识
    18)PHP,可变函数,匿名函数 变量的作用域
    17)PHP,函数基础和参数问题
    16)PHP, set_include_path
  • 原文地址:https://www.cnblogs.com/zpchcbd/p/12374083.html
Copyright © 2020-2023  润新知