[oldboy-django][2深入django]xss攻击 + csrf
1 xss攻击
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()</script>,#}
{# 就会弹出框123(真正的做法是获取cookie,然后别人就可以用你的账户登录网站了,那时候就麻烦)#}
{% endfor %}
</body>
2 csrf
csrf(跨站网站请求伪造)
- 情景: 盗取方自己建立一个网站,上面有一个图片链接
<a href="http://www.cmbchina.com/?to=652222287448748&money=1999999><img></img></a> 上面的链接是招商银行的转账链接, 如果招商银行用户在自己网页登录了招商银行,在没有退出的情况下,
点击上面的图片,就会自动转账到用户6522222874487848,1999999金额 招商银行解决办法:
采用POST,需要自己输入表单
盗取方同样有方法
<form>
<input type='text' name='to' value='' style='display:none'>
<input type='text' name='money' value='' style='display:none'>
<a onclick="ff()"> <img></img>
</a>
</form> 采用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
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 - 添加装饰器方式
. 在类里面的多个函数添加
class Foo(View): @method_decorator(wrapper)
def get(self,request):
pass @method_decorator(wrapper)
def post(self,request):
pass .对类的多个函数都添加装饰器
@method_decorator(wrapper, name='post')
@method_decorator(wrapper, name='get')
class Foo(View): .对类所有函数添加装饰器
@method_decorator(wrapper, name='dispatch')
class Foo(View): # 请求来了,到dispatch函数,dispatch根据反射调用不同的函数
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>
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)
}
})
}
5 补充csrf基本使用方法
- 补充csrf的基本使用方式
# 'django.middleware.csrf.CsrfViewMiddleware'
在视图函数上
from django.views.decorators.csrf import csrf_protect
@csrf_protect
def crsf1(request):
pass
在csrf1.html中的form表单中
添加{% crsf_token %}
否则会报以下错误
英文解析Forbidden ()
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.
[oldboy-django][2深入django]xss攻击 + csrf的更多相关文章
- 第三百九十二节,Django+Xadmin打造上线标准的在线教育平台—sql注入攻击,xss攻击,csrf攻击
第三百九十二节,Django+Xadmin打造上线标准的在线教育平台—sql注入攻击,xss攻击,csrf攻击 sql注入攻击 也就是黑客通过表单提交的地方,在表单里输入了sql语句,就是通过SQL语 ...
- Django是如何防止注入攻击-XSS攻击-CSRF攻击
注入攻击-XSS攻击-CSRF攻击介绍请访问:https://www.cnblogs.com/hwnzy/p/11219475.html Django防止注入攻击 Django提供一个抽象的模型层来组 ...
- XSS攻击&CSRF攻击 ----Django解决方案
XSS攻击: XSS又叫CSS (Cross Site Script) ,跨站脚本攻击.它指的是恶意攻击者往Web页面里插入恶意html代码,当用户浏览该页之时,嵌入其中Web里面的html代码会被执 ...
- Django项目开发,XSS攻击,图片防盗链,图片验证码,kindeditor编辑器
目录 一.Django项目开发 1. 项目开发流程 2. auth模块的补充 (1)django的admin可视化管理页面 (2)将admin可视化管理页面的模型表显示成中文 (3)auth模块的用户 ...
- XSS攻击 CSRF攻击
XSS攻击: 跨站脚本攻击(Cross Site Scripting),为不和层叠样式表(Cascading Style Sheets, CSS)的缩写混淆, 故将跨站脚本攻击缩写为XSS.恶意攻击者 ...
- XSS攻击 && CSRF攻击 基础理解
一个网站,不管多么的帅气,多么的风骚,如果你不安全,那始终都是一个弟弟啊~ 今天又看了下XSS和CSRF攻击的文章,我也想发点什么普及下大家的安全意识,毕竟作为一名拥有伟大梦想的程序员,基本的安全意识 ...
- 注入攻击-XSS攻击-CSRF攻击
1.注入攻击 注入攻击包括系统命令注入,SQL注入,NoSQL注入,ORM注入等 1.1攻击原理 在编写SQL语句时,如果直接将用户传入的数据作为参数使用字符串拼接的方式插入到SQL查询中,那么攻击者 ...
- XSS和CSRF的理解
声明:转自 http://www.cnblogs.com/hyddd/archive/2009/04/09/1432744.html XSS攻击:跨站脚本攻击(Cross Site Scripting ...
- Django—XSS及CSRF
一.XSS 跨站脚本攻击(Cross Site Scripting),为不和层叠样式表(Cascading Style Sheets, CSS)的缩写混淆,故将跨站脚本攻击缩写为XSS.恶意攻击者往W ...
随机推荐
- CentOs7 修复 引导启动
一.修复MBR: MBR(Master Boot Record主引导记录): 硬盘的0柱面.0磁头.1扇区称为主引导扇区.其中446Byte是bootloader,64Byte为Partition t ...
- hadoop2.4 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
在Ubuntu上安装完hadoop2.4以后,使用以下命令: hadoop fs -ls // :: WARN util.NativeCodeLoader: Unable to load native ...
- IOS PickerView使用
- (void)viewDidLoad { [super viewDidLoad]; // 1.创建pickerview // pickerview有默认的frame UIPickerView *pi ...
- 使用RichTextBox控件保存文件
实习效果: 知识运用: RichTextBox控件的SaveFile方法 SaveFileDialog对象的ShowDialog方法 实现代码: private void 打开RTF文件ToolStr ...
- fast rcnn训练自己数据小结
1.http://blog.csdn.net/hao529good/article/details/46544163 我用的训练好的模型参数是data/fast_rcnn__models/vgg_ ...
- 如何在python中读写和存储matlab的数据文件(*.mat)
使用sicpy.io即可.sicpy.io提供了两个函数loadmat和savemat,非常方便. 以前也有一些开源的库(pymat和pymat2等)来做这个事, 不过自从有了numpy和scipy以 ...
- javascript同步和异步的区别与实现方式
javascript语言是单线程机制.所谓单线程就是按次序执行,执行完一个任务再执行下一个. 对于浏览器来说,也就是无法在渲染页面的同时执行代码. 单线程机制的优点在于实现起来较为简单,运行环境相对简 ...
- 题解 P2626 【斐波那契数列(升级版)】
这道题,大家一定要注意: 要对2^31取模 ! ( 本蒟蒻开始没注意到这一点,WA了 ) (不过大家在试样例的时候,试试47,出不了结果,就说明你没模2^31) 总体来说,这道题考查的知识点就两个: ...
- Java控制语句例题,for循环语句,if条件语句等,Scanner类与Random类,Math.max()方法
例题:编写程序,生成5个1至10之间的随机整数,并打印结果到控制台 import java.util.Random;class demo09 { public static void main(Str ...
- Git笔记(流水账)
命令git checkout -- readme.txt意思就是,把readme.txt文件在工作区的修改全部撤销,这里有两种情况: 一种是readme.txt自修改后还没有被放到暂存区,现在,撤销修 ...