zoukankan      html  css  js  c++  java
  • [oldboy-django][2深入django]xss攻击 + csrf

    1 xss攻击

    5 xss攻击(跨站脚本攻击,用户页面提交数据来盗取cookie)
        - 慎用safe, 和mark_safe
            -- 如果要用,必须要过滤
    
        - 定义:
            用户提交内容,在页面展示用html显示的时候
            页面提交一些script脚本,盗取cookie
            
            # views
            msg = []
            def xss(request):
                if request.method == "GET":
                    return render(request, 'xss.html')
                else:
                    tmp = request.POST.get('content')
                    msg.append(tmp)
                    print(tmp)
                    return render(request, 'xss.html')
                    
            def content_index(request):
                print(msg)
                return render(request, 'content_index.html', {'msg':msg})
              
            # templates
                <body>
                    <h2>评论</h2>
                    <form action="/xss.html" method="POST">
                        <input type="text" placeholder="请输入评论" name="content">
                        <input type="submit" value="提交">
                    </form>
                </body>  
                
                <body>
                    <h2>评论</h2>
                    {% for item in msg %}
                        <div>{{ item }}</div>
                {#        <div>{{ item|safe }}</div>#}
                {#            django已经阻止xss攻击了,#}
                {#        如果使用item|safe,那就麻烦了:此时用户提交评论<script>alert(123)</script>,#}
                {#        就会弹出框123(真正的做法是获取cookie,然后别人就可以用你的账户登录网站了,那时候就麻烦)#}
                    {% endfor %}
                </body>
    View Code

    2 csrf

    6 csrf(跨站网站请求伪造)
        - 情景: 盗取方自己建立一个网站,上面有一个图片链接
                <a href="http://www.cmbchina.com/?to=652222287448748&money=1999999><img></img></a>
    
                上面的链接是招商银行的转账链接, 如果招商银行用户在自己网页登录了招商银行,在没有退出的情况下,
                点击上面的图片,就会自动转账到用户6522222874487848,1999999金额
    
                招商银行解决办法:
                    1 采用POST,需要自己输入表单
                        盗取方同样有方法
                            <form>
                                <input type='text' name='to' value='652222287448748' style='display:none'>
                                <input type='text' name='money' value='652222287448748' style='display:none'>
                                <a onclick="ff()"> <img></img>
                                 </a>
                            </form>
    
                    2 采用csrf方法,
                        用户登录后,点击转账按钮,GET请求到转账页面,招商银行后台会一个随机字符串写在页面上,
                        然后提交表单的时候,同时将这个字符串提交给后台 {% crsf_token %};当然这个字符串是隐藏的
    
        - 使用方式
            a. 基本应用(解除settings.py)
                 'django.middleware.csrf.CsrfViewMiddleware'
                 在表单上{% crsf_token %}
    
            b. 全部禁用
                #'django.middleware.csrf.CsrfViewMiddleware'
    
            c. 局部禁用
                - 'django.middleware.csrf.CsrfViewMiddleware'
    
                - 对test函数禁用csrf
                    from django.views.decorators.csrf import csrf_exempt
                    @csrf_exempt
                    def test(request):
                        pass
    
                - 对类Foo所有函数禁用
                    from django.views.decorators.csrf import csrf_exempt
                    from django.utils.decorators import method_decorator
    
                    @method_decorator(csrf_exempt, name='dispatch')
                    def test(request):
                        pass
    
            d. 局部使用
                - #'django.middleware.csrf.CsrfViewMiddleware'
    
                - 对test函数使用
                    from django.views.decorators.csrf import csrf_protect
    
                    @csrf_protect
                    def test(request):
                        pass
    
                - 对类Foo所有函数使用(只支持这种)
                    from django.views.decorators.csrf import csrf_protect
                    from django.utils.decorators import method_decorator
    
                    @method_decorator(csrf_protect, name='dispatch')
                    def test(request):
                        pass
    View Code

    2 补充csrf攻击原理:

    2 补充csrf防范机制

    3 补充cbv添加装饰器的方法

            ps CBV添加装饰器方法
                - 定义装饰器
                def wrapper(func):
                    def inner(*args, **kwargs):
                       return func(*args, **kwargs)
                    return inner
    
                - 导入django使用FBV装饰器的方法
                    from django.utils.decorators import method_decorator
    
                - 添加装饰器方式
                    1. 在类里面的多个函数添加
                        class Foo(View):
    
                            @method_decorator(wrapper)
                            def get(self,request):
                                pass
    
                            @method_decorator(wrapper)
                            def post(self,request):
                                pass
    
                    2.对类的多个函数都添加装饰器
                        @method_decorator(wrapper, name='post')
                        @method_decorator(wrapper, name='get')
                        class Foo(View):
    
    
                    3.对类所有函数添加装饰器
                        @method_decorator(wrapper, name='dispatch')
                        class Foo(View):
    
                        # 请求来了,到dispatch函数,dispatch根据反射调用不同的函数
    View Code

     4 如何将csrf中隐藏的字符串发给后台(form表单 + ajax请求)

      4.1 form表单

    <form action="/csrf1.html" method="POST">
        {% csrf_token %}
    {#    # 如果没有这句,会报错#}
        <input type="text" name="username" placeholder="用户名" id="user">
        <input type="password" name="pwd" placeholder="密码" >
        <input type="submit" value="form提交">
    </form>
    View Code

      4.2 ajax提交

        - csrf(ajax请求)
    
            a. ajax发送crsf, 数据携带csrf
                <form action="/csrf1.html" method="POST">
                    {% csrf_token %}
                    <input type="text" name="username" placeholder="用户名" id="user">
                    <input type="password" name="pwd" placeholder="密码" >
                    <a onclick="submit_ajax()">ajax提交</a>
                </form>
    
                function  submit_ajax() {
                    var csrf_token = $('input[name="csrfmiddlewaretoken"]').val();
                    var user = $('#user').val();
                    $.ajax({
                        url: '/csrf1.html',
                        type: 'POST',
                        data: {'username': user, 'csrfmiddlewaretoken': csrf_token},
                        success: function (arg) {
                            console.log(arg)
                        }
                    })
                }
    
            b. ajax发送csrf, 消息头携带cookie的csrf
                获取cookie里面的csrftoken, 并在请求头里面设置X-CSRFToken: csrftoken
                前端js获取cookie,需要引入插件jquery.cookie.js
    
                function submit_ajax() {
                    var token = $.cookie('csrftoken');
                    var user = $('#user').val();
                    $.ajax({
                        url: '/csrf1.html',
                        type: 'POST',
                        headers:{'X-CSRFToken': token},
                        data: {'username': user},
                        success: function (arg) {
                            console.log(arg)
                        }
                    })
    
                }
    View Code

    5 补充csrf基本使用方法

       - 补充csrf的基本使用方式
    
            1 # 'django.middleware.csrf.CsrfViewMiddleware'
    
            2 在视图函数上
                from django.views.decorators.csrf import csrf_protect
                @csrf_protect
                def crsf1(request):
                    pass
    
            3 在csrf1.html中的form表单中
                添加{% crsf_token %}
    
    
            4 否则会报以下错误
    
                英文解析Forbidden (403)
                CSRF verification failed. Request aborted.
                You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.
                If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests.
                Help
                Reason given for failure:
                    CSRF cookie not set.
    
                In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:
                    Your browser is accepting cookies.
                    The view function passes a request to the template's render method.
                    In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
                    If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
                    The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.
                    You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.
                    You can customize this page using the CSRF_FAILURE_VIEW setting.
    View Code
  • 相关阅读:
    Oracle9i数据库移动过程
    基于索引的SQL语句优化之降龙十八掌
    activex发布步骤
    用ftpsupport进行ftp上传
    周五晚上看了变形金刚
    故宫游
    UTF8转GB2312
    跨数据库的视图【自己留着看】
    数学之美 - 布隆过滤器(Bloom Filter)【转】
    搜索引擎优化SEO的ppt讲义
  • 原文地址:https://www.cnblogs.com/liuzhipenglove/p/7777074.html
Copyright © 2011-2022 走看看