django安全-xss和csrf
XSS
XSS跨站脚本攻击(Cross Site Scripting),为不和层叠样式表(Cascading Style Sheets, CSS)的缩写混淆,故将跨站脚本攻击缩写为XSS。恶意攻击者往Web页面里插入恶意Script代码,当用户浏览该页之时,嵌入其中Web里面的Script代码会被执行,从而达到恶意攻击用户的目的。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 ##############xss攻击############# 2 3 4 **************************************** 5 #不带if判断进行关键字过滤代码 6 msg=[] 7 def comment(request): 8 if request.method =="GET": 9 return render(request,'comment.html') 10 else: 11 v = request.POST.get('content') 12 msg.append(v) 13 return render(request,'comment.html') 14 def index(request): 15 return render(request,'index.html',{'msg':msg}) 16 ***************************************** 17 18 ***************************************** 19 #带if判断进行关键字过滤代码 20 msg=[] 21 def comment(request): 22 if request.method =="GET": 23 return render(request,'comment.html') 24 else: 25 v = request.POST.get('content') 26 if "script" in v: 27 return render(request,'comment.html',{'error':'黑你大爷'}) 28 else: 29 msg.append(v) 30 return render(request, 'comment.html') 31 def index(request): 32 return render(request,'index.html',{'msg':msg}) 33 ********************************************* 34 35 ********************************************* 36 #测试: 37 38 def test(request): 39 from django.utils.safestring import mark_safe 40 temp = "<a href='http://www.baidu.com'>百度</a>" 41 newtemp = mark_safe(temp) 42 return render(request, 'test.html', {'temp': newtemp}) 43 44 ******************************************** 45 注: 46 47 # 1.用<script>alert(11222)</script>模拟攻击代码 48 # 2.过滤攻击方式: 49 a.在接受评论端(前端代码)不要写 |safe. 50 比如:<div>{{ item|safe }}</div> 51 52 #b.在后台代码中进行if关键字过滤判断 53 54 55 3.test.html: 56 # 里面如果不加|safe,渲染出来的只是普通字符“ 57 <a href='http://www.baidu.com'>百度</a>” 58 # 如果加|safe,渲染出来的是<a>标签连接 59 #后端标记字符串安全: 60 (前端不加safe,后端加safe) 61 #导入模块 :from django.utils.safestring import mark_safe 62 #说明安全:ewtemp = mark_safe(temp) 63 64 Views
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <form method="POST" action="/comment/"> 9 <input type="text" name="content"> 10 <input type="submit" value="提交"/>{{ error }} 11 </form> 12 </body> 13 </ht 14 15 comment.html
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <h3>评论</h3> 9 {% for item in msg %} 10 11 <div>{{ item }}</div> 12 13 {# <div>{{ item|safe }}</div>#} 14 15 {% endfor %} 16 </body> 17 </ht 18 19 index.html
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 {# {{ temp|safe }}#} 9 {{ temp }} 10 </body> 11 </htm 12 13 test.html
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 """day73 URL Configuration 2 3 The `urlpatterns` list routes URLs to views. For more information please see: 4 https://docs.djangoproject.com/en/1.10/topics/http/urls/ 5 Examples: 6 Function views 7 1. Add an import: from my_app import views 8 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 9 Class-based views 10 1. Add an import: from other_app.views import Home 11 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 12 Including another URLconf 13 1. Import the include() function: from django.conf.urls import url, include 14 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 15 """ 16 from django.conf.urls import url 17 from django.contrib import admin 18 19 from app01 import views 20 21 22 urlpatterns = [ 23 url(r'^admin/', admin.site.urls), 24 url(r'^test/',views.test), 25 url(r'^comment/',views.comment), 26 url(r'^index/',views.index), 27 28 ] 29 30 urls
CSRF
CSRF(Cross-site request forgery)跨站请求伪造,也被称为“One Click Attack”或者Session Riding,通常缩写为CSRF或者XSRF,是一种对网站的恶意利用。尽管听起来像跨站脚本(XSS),但它与XSS非常不同,XSS利用站点内的信任用户,而CSRF则通过伪装来自受信任用户的请求来利用受信任的网站。与XSS攻击相比,CSRF攻击往往不大流行(因此对其进行防范的资源也相当稀少)和难以防范,所以被认为比XSS更具危险性。
解决方案:
方式一:form表单内第一行添加
# { % csrf_token %}
方式二:全局禁用,在设置settings文件中中间件部分找到如下csrf注释掉
# 'django.middleware.csrf.CsrfViewMiddleware',
方式三:模块装饰器局部禁用
# 'django.middleware.csrf.CsrfViewMiddleware', 先注释掉全局 # from django.views.decorators.csrf import csrf_exempt # @csrf_exempt # def csrf1(request): # if request.method == 'GET': # return render(request, 'csrf1.html') # else: # return HttpResponse('ok')
# ****************局部使用************************* # d.(全站禁用前提下可以使用局部使用) # 'django.middleware.csrf.CsrfViewMiddleware', # from django.views.decorators.csrf import csrf_protect # @csrf_protect # def csrf1(request): # if request.method == 'GET': # return render(request, 'csrf1.html') # else: # return HttpResponse('ok') # ************************************************
CBV中添加装饰器
#****************CBV中添加装饰器******************** # c.特殊CBV # from django.views import View # from django.utils.decorators import method_decorator # @method_decorator(csrf_protect, name='dispatch') # class Foo(View): # def get(self, request): # pass # # def post(self, request): # pass # def wrapper(func): # def inner(*args,**kwargs): # return func(*args,**kwargs) # return inner # 1. 指定方法上添加装饰器 # class Foo(View): # @method_decorator(wrapper) # def get(self,request): # pass # def post(self,request): # pass # 2. 在类上添加 # @method_decorator(wrapper,name='dispatch') #全部类添加 # @method_decorator(wrapper, name='get') # 只给get添加 # @method_decorator(wrapper, name='post') # 只给post添加 # class Foo(View): # def dispatch(self,request,*args,**kwargs) # pass # def get(self,request): # pass # def post(self,request): # pass
注意ajax 请求:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="POST" action="/csrf1.html/"> {% csrf_token %} <input type="text" name="user"> <input type="submit" value="提交"/> <a onclick="submitForm();">Ajax提交</a> </form> <script src="/static/jquery-3.2.1.js"></script> <script src="/static/jquery.cookie.js"></script> <script> 第一种方式: function submitForm() { var csrf = $('input[name="csrfmiddlewaretoken"]').val(); var user = $('#user').val(); $.ajax({ url:'/csrf1.html', type:'POST', data:{"user":user,'csrfmiddlewaretoken':csrf}, success:function (arg) { console.log(arg); } }) } 第二种方式: {# 获取Console值:在浏览器Console上输入document.cookie#} function submitForm() { var token = $.cookie('csrftoken'); var csrf = $('input[name="csrfmiddlewaretoken"]').val(); var user = $('#user').val(); $.ajax({ url:'/csrf1.html', type:'POST', headers:{'X-CSRFToken':token}, data:{"user":user}, success:function (arg) { console.log(arg); } }) } </script> </body> </html>
def csrf1(request): if request.method == 'GET': return render(request,'csrf1.html') else: return HttpResponse('哥们干啥来了')