Home > Backend Development > Python Tutorial > Detailed introduction to XSS and CSRF

Detailed introduction to XSS and CSRF

零下一度
Release: 2017-06-29 10:40:25
Original
2729 people have browsed it

1. Malicious attackers insert malicious Script code into a Web page. When a user browses the page, the Script code embedded in the Web page will be executed, thereby achieving the purpose of maliciously attacking the user.

1. Workflow

a. Malicious users enter some text in some public areas (for example, the input form of the suggestion submission form or the message public board), which is seen by other users. , but these texts are not only the text they want to input, but also include some scripts that can be executed on the client side. For example:

<script>'Not Safe'</script>
Copy after login
b. Malicious submission of this form

c. Other users see this page containing malicious scripts and execute them to obtain the user's cookies, etc. Sensitive information.

2. Example - Failure to prevent XSS attacks

 1 pinglu = []     # 评论列表 2  3 #提交表单 4 def commit(request): 5     if request.method == 'GET': 6         return render(request, 'commit.html') 7     else: 8         com = request.POST.get('commit') 9         pinglu.append(com)10         return redirect('/index.html/')11 12 13 #查看评论页面14 def index(request):15     return render(request, 'index.html', {'commit': pinglu})
Copy after login
view.py
##
 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4     <meta charset="UTF-8"> 5     <title>Title</title> 6 </head> 7 <body> 8 <h1>评论</h1> 9 <form action="/commit.html/" method="post">10     <input type="text" name="commit">11     <input type="submit" value="sumbit"> {{ error }}12 </form>13 </body>14 </html>
Copy after login
commit.html
 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4     <meta charset="UTF-8"> 5     <title>Title</title> 6 </head> 7 <body> 8 <h1>评论</h1> 9 {% for item in commit %}10     <div>{{ item|safe }}</div>11 {#    item后加safe,默认数据安全,django不会做特殊处理#}12 {% endfor %}13 </body>14 </html>
Copy after login
index.html
In the above example, if you enter the following content on the commit.html page and submit:
<script> alert('恶意脚本') </script>
Copy after login

will execute this line of code on the index page, and a warning box will pop up (if it contains malicious code, it will be executed)

3. Prevent XSS attacks

    The most direct way is not to use safe
  • {#    <div>{{ item|safe }}</div>#}<div>{{ item }}</div>
    Copy after login
    ## for uncontrollable input in the html page
#You can also filter in views to prevent special characters from being submitted to the database or web page
  • def commit(request):if request.method == 'GET':return render(request, 'commit.html')else:
            com = request.POST.get('commit')if '<script>' in com:    # 过滤“<script>”关键字,防止恶意代码的提交return render(request, 'commit.html', {'error': '此条评论有毒,已被和谐'})else:
                pinglu.append(com)return redirect('/index.html/')
    Copy after login

2. CSRF

CSRF (Cross-site request forgery) cross-site request forgery, also known as "One Click Attack" or Session Riding, often abbreviated as CSRF or XSRF, is a malicious exploitation of a website. Although it sounds like cross-site scripting (XSS), it is very different from XSS, which exploits trusted users within a site, while CSRF exploits trusted websites by disguising requests from trusted users. Compared with XSS attacks, CSRF attacks tend to be less popular (so resources to prevent them are also quite scarce) and difficult to prevent, so they are considered more dangerous than XSS.

1. Workflow

The attack works by including links or scripts in pages accessed by authorized users:

2. How to prevent in django

Django implements the function of preventing cross-site request forgery for users, which is completed through the middleware django.middleware.csrf.CsrfViewMiddleware. The anti-cross-site request forgery function in Django is divided into global and local.

Global:

Enable middleware django.middleware.csrf.CsrfViewMiddleware
  • ##Partial:

from django.views.decorators.csrf import csrf_exempt,csrf_protect
Copy after login
  • @csrf_protect,为当前函数强制设置防跨站请求伪造功能,即便settings中没有设置全局中间件

  • @csrf_exempt,取消当前函数防跨站请求伪造功能,即便settings中设置了全局中间件。

 3. django中的具体应用方法

  • form表单中添加{csrf_token %}

若form表单中未添加{csrf_token %},则会报403错误。

#settings.py中打开MIDDLEWARE设置'django.middleware.csrf.CsrfViewMiddleware',
Copy after login
1 from django.shortcuts import render, HttpResponse, redirect2 3 def csrf_test(request):4     if request.method == 'GET':5         return render(request, 'csrf_test.html')6     else:7         return HttpResponse('ok')
Copy after login
views.py
 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4     <meta charset="UTF-8"> 5     <title>csef_test</title> 6 </head> 7 <body> 8 <form action="/csrf_test.html/" method="post"> 9     <input type="text" name="user" id="user">10     <input type="submit" value="submit">11 </form>12 13 </body>14 </html>
Copy after login
csef_test.html

修改csef_test.html:

 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4     <meta charset="UTF-8"> 5     <title>csef_test</title> 6 </head> 7 <body> 8 <form action="/csrf_test.html/" method="post"> 9     {% csrf_token %}10     <input type="text" name="user" id="user">11     <input type="submit" value="submit">12 </form>13 14 </body>15 </html>
Copy after login
form表单中添加{% csrf_token %}

  • 全站禁用,即将settings.py中的 'django.middleware.csrf.CsrfViewMiddleware' 注释掉即可

  • 基于FBV视图的局部禁用和使用

 1 #settings.py 2 #启用 'django.middleware.csrf.CsrfViewMiddleware', 3  4  5 from django.views.decorators.csrf import csrf_exempt 6  7  8 @csrf_exempt 9 def csrf_test(request):10     if request.method == 'GET':11         return render(request, 'csrf_test.html')12     else:13         return HttpResponse('ok')
Copy after login
局部禁用
 1 #settings.py 2 #禁用 #'django.middleware.csrf.CsrfViewMiddleware', 3  4  5 from django.views.decorators.csrf import csrf_protect 6  7  8 @csrf_protect 9 def csrf_test(request):10     if request.method == 'GET':11         return render(request, 'csrf_test.html')12     else:13         return HttpResponse('ok')
Copy after login
局部使用
  •  基于CBV视图的(只能局部使用或禁用类,不能在类方法里局部使用或禁用

 1 #settings.py 2 #禁用    'django.middleware.csrf.CsrfViewMiddleware', 3  4  5 from django.views import View 6 from django.views.decorators.csrf import csrf_protect 7 from django.utils.decorators import method_decorator 8  9 10 @method_decorator(csrf_protect, name='dispatch')11 class Foo(View):12     def get(self, request):13         pass14 15     def post(self, request):16         pass
Copy after login
局部使用
 1 #settings.py 2 #启用    'django.middleware.csrf.CsrfViewMiddleware', 3  4  5 from django.views import View 6 from django.views.decorators.csrf import csrf_exempt 7 from django.utils.decorators import method_decorator 8  9 10 @method_decorator(csrf_exempt, name='dispatch')11 class Foo(View):12     def get(self, request):13         pass14 15     def post(self, request):16         pass
Copy after login
局部禁用
  • Ajax提交数据时,携带CSRF

 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4     <meta charset="UTF-8"> 5     <title>csef_test</title> 6 </head> 7 <body> 8 <form action="/csrf_test.html/" method="post"> 9     {% csrf_token %}10     <input type="text" name="user" id="user">11 {#    <input type="submit" value="submit">#}12     <a onclick="submitForm();">Ajax提交表单</a>13 </form>14 15 <script src="/static/jquery-3.2.1.js"></script>16 <script>17     function submitForm() {18             var csrf = $("input[name='csrfmiddlewaretoken']").val()19             var user = $("#user").val()20             $.ajax({21                 url: '/csrf_test.html/',22                     type: 'POST',23                     data: {"user": user, "csrfmiddlewaretoken": csrf},24                     success: function (arg) {25                             console.log(arg);26           }27             })28   }29 </script>30 </body>31 </html>
Copy after login
Ajax重写csrf_test,html,csrf数据存放于data中
 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4     <meta charset="UTF-8"> 5     <title>csef_test</title> 6 </head> 7 <body> 8 <form action="/csrf_test.html/" method="post"> 9     {% csrf_token %}10     <input type="text" name="user" id="user">11 {#    <input type="submit" value="submit">#}12     <a onclick="submitForm();">Ajax提交表单</a>13 </form>14 15 <script src="/static/jquery-3.2.1.js"></script>16 {#专门处理cookie的插件,提取cookie字符串#}17 <script src="/static/jquery.cookie.js"></script>18 19 {#csrf数据放于data中#}20 {#<script>#}21 {#    function submitForm() {#}22 {#            var csrf = $("input[name='csrfmiddlewaretoken']").val();#}23 {#            var user = $("#user").val();#}24 {#            $.ajax({#}25 {#                url: '/csrf_test.html/',#}26 {#                    type: 'POST',#}27 {#                    data: {"user": user, "csrfmiddlewaretoken": csrf},#}28 {#                    success: function (arg) {#}29 {#                            console.log(arg);#}30 {#          }#}31 {#            })#}32 {#  }#}33 {#</script>#}34 35 {#csrf数据放于请求头中#}36 <script>37     function submitForm() {38             var csrf = $.cookie('csrftoken');39             var user = $("#user").val();40             $.ajax({41                 url: '/csrf_test.html/',42                     type: 'POST',43                     headers: {'X-CSRFToken': csrf},44                     data: {"user": user},45                     success: function (arg) {46                             console.log(arg);47           }48             })49   }50 </script>51 52 53 54 </body>55 </html>
Copy after login
Ajax重写csrf_test.html,csrf数据存放于headers中

注意:{csrf_token %}和cookie中的csrftoken值不一样。

form表单中的隐藏csrf_token

 cookie中

 

The above is the detailed content of Detailed introduction to XSS and CSRF. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template