跨站腳本攻擊(Cross Site Scripting),為不和層疊樣式表(Cascading Style Sheets, CSS)的縮寫混淆,故將跨站腳本攻擊縮寫為XSS。惡意攻擊者往Web頁面插入惡意Script程式碼,當使用者瀏覽該頁之時,嵌入其中Web裡面的Script程式碼會被執行,從而達到惡意攻擊使用者的目的。
a. 惡意用戶,在一些公共區域(例如,建議提交表單或訊息公共板的輸入表單)輸入一些文本,這些文本被其它用戶看到,但這些文本不僅僅是他們要輸入的文本,同時還包括一些可以在客戶端執行的腳本。如:
<script>'Not Safe'</script>
b. 惡意提交這個表單
c. 其他使用者看到這個包含惡意腳本的頁面並執行,取得使用者的cookie等敏感資訊。
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})
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>
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>
以上實例中,若在commit.html頁面輸入以下內容並提交:
<script> alert('恶意脚本') </script>
則會在index頁面執行此行程式碼,彈出警告框(若包含惡意程式碼,執行)
最直接的方法就是對於無法控制的輸入在html頁面內不要使用safe
{# <div>{{ item|safe }}</div>#}<div>{{ item }}</div>
也可以在views裡過濾,防止特殊字元提交到資料庫或網頁內
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/')
#啟用中間件 django.middleware.csrf.CsrfViewMiddleware
from django.views.decorators.csrf import csrf_exempt,csrf_protect
@csrf_protect,为当前函数强制设置防跨站请求伪造功能,即便settings中没有设置全局中间件
@csrf_exempt,取消当前函数防跨站请求伪造功能,即便settings中设置了全局中间件。
form表单中添加{
%
csrf_token
%
}
若form表单中未添加{
%
csrf_token
%
},则会报403错误。
#settings.py中打开MIDDLEWARE设置'django.middleware.csrf.CsrfViewMiddleware',
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')
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>
修改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>
全站禁用,即将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')
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')
基于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
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
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>
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>
注意:{
%
csrf_token
%
}和cookie中的csrftoken值不一样。
form表单中的隐藏csrf_token
cookie中
以上是XSS及CSRF的詳細介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!