Django : Security in Django
Security in Django
1
Cross site scripting (XSS) protection¶
跨站脚本攻击
XSS attacks allow a user to inject client side scripts into the browsers of other users. This is usually achieved by storing the malicious scripts in the database where it will be retrieved and displayed to other users, or by getting users to click a link which will cause the attacker’s JavaScript to be executed by the user’s browser. However, XSS attacks can originate from any untrusted source of data, such as cookies or Web services, whenever the data is not sufficiently sanitized before including in a page.
Using Django templates protects you against the majority of XSS attacks. However, it is important to understand what protections it provides and its limitations.
Django templates escape specific characters which are particularly dangerous to HTML. While this protects users from most malicious input, it is not entirely foolproof. For example, it will not protect the following:
<style class={{ var }}>...</style>If
var
is set to'class1 onmouseover=javascript:func()'
, this can result in unauthorized JavaScript execution, depending on how the browser renders imperfect HTML. (Quoting the attribute value would fix this case.)It is also important to be particularly careful when using
is_safe
with custom template tags, thesafe
template tag,mark_safe
, and when autoescape is turned off.In addition, if you are using the template system to output something other than HTML, there may be entirely separate characters and words which require escaping.
You should also be very careful when storing HTML in the database, especially when that HTML is retrieved and displayed.
Cross site request forgery (CSRF) protection¶
跨站请求伪造
CSRF attacks allow a malicious user to execute actions using the credentials of another user without that user’s knowledge or consent.
Django has built-in protection against most types of CSRF attacks, providing you have enabled and used it where appropriate. However, as with any mitigation technique, there are limitations. For example, it is possible to disable the CSRF module globally or for particular views. You should only do this if you know what you are doing. There are other limitations if your site has subdomains that are outside of your control.
CSRF protection works by checking for a secret in each POST request. This ensures that a malicious user cannot simply “replay” a form POST to your website and have another logged in user unwittingly submit that form. The malicious user would have to know the secret, which is user specific (using a cookie).
When deployed with HTTPS,
CsrfViewMiddleware
will check that the HTTP referer header is set to a URL on the same origin (including subdomain and port). Because HTTPS provides additional security, it is imperative to ensure connections use HTTPS where it is available by forwarding insecure connection requests and using HSTS for supported browsers.Be very careful with marking views with the
csrf_exempt
decorator unless it is absolutely necessary.SQL injection protection¶
SQL 注入
SQL injection is a type of attack where a malicious user is able to execute arbitrary SQL code on a database. This can result in records being deleted or data leakage.
By using Django’s querysets, the resulting SQL will be properly escaped by the underlying database driver. However, Django also gives developers power to write raw queries or execute custom sql. These capabilities should be used sparingly and you should always be careful to properly escape any parameters that the user can control. In addition, you should exercise caution when using
extra()
andRawSQL
.Clickjacking protection¶
点击劫持
Clickjacking is a type of attack where a malicious site wraps another site in a frame. This attack can result in an unsuspecting user being tricked into performing unintended actions on the target site.
Django contains clickjacking protection in the form of the
X-Frame-Options middleware
which in a supporting browser can prevent a site from being rendered inside a frame. It is possible to disable the protection on a per view basis or to configure the exact header value sent.The middleware is strongly recommended for any site that does not need to have its pages wrapped in a frame by third party sites, or only needs to allow that for a small section of the site.
SSL/HTTPS¶
安全/加密传输
It is always better for security to deploy your site behind HTTPS. Without this, it is possible for malicious network users to sniff authentication credentials or any other information transferred between client and server, and in some cases – activenetwork attackers – to alter data that is sent in either direction.
If you want the protection that HTTPS provides, and have enabled it on your server, there are some additional steps you may need:
If necessary, set
SECURE_PROXY_SSL_HEADER
, ensuring that you have understood the warnings there thoroughly. Failure to do this can result in CSRF vulnerabilities, and failure to do it correctly can also be dangerous!Set
SECURE_SSL_REDIRECT
toTrue
, so that requests over HTTP are redirected to HTTPS.Please note the caveats under
SECURE_PROXY_SSL_HEADER
. For the case of a reverse proxy, it may be easier or more secure to configure the main Web server to do the redirect to HTTPS.Use ‘secure’ cookies.
If a browser connects initially via HTTP, which is the default for most browsers, it is possible for existing cookies to be leaked. For this reason, you should set your
SESSION_COOKIE_SECURE
andCSRF_COOKIE_SECURE
settings toTrue
. This instructs the browser to only send these cookies over HTTPS connections. Note that this will mean that sessions will not work over HTTP, and the CSRF protection will prevent any POST data being accepted over HTTP (which will be fine if you are redirecting all HTTP traffic to HTTPS).Use HTTP Strict Transport Security (HSTS)
HSTS is an HTTP header that informs a browser that all future connections to a particular site should always use HTTPS. Combined with redirecting requests over HTTP to HTTPS, this will ensure that connections always enjoy the added security of SSL provided one successful connection has occurred. HSTS may either be configured with
SECURE_HSTS_SECONDS
andSECURE_HSTS_INCLUDE_SUBDOMAINS
or on the Web server.Host header validation¶
主机头部验证
Django uses the
Host
header provided by the client to construct URLs in certain cases. While these values are sanitized to prevent Cross Site Scripting attacks, a fakeHost
value can be used for Cross-Site Request Forgery, cache poisoning attacks, and poisoning links in emails.Because even seemingly-secure web server configurations are susceptible to fake
Host
headers, Django validatesHost
headers against theALLOWED_HOSTS
setting in thedjango.http.HttpRequest.get_host()
method.This validation only applies via
get_host()
; if your code accesses theHost
header directly fromrequest.META
you are bypassing this security protection.For more details see the full
ALLOWED_HOSTS
documentation.Warning
Previous versions of this document recommended configuring your web server to ensure it validates incoming HTTP
Host
headers. While this is still recommended, in many common web servers a configuration that seems to validate theHost
header may not in fact do so. For instance, even if Apache is configured such that your Django site is served from a non-default virtual host with theServerName
set, it is still possible for an HTTP request to match this virtual host and supply a fakeHost
header. Thus, Django now requires that you setALLOWED_HOSTS
explicitly rather than relying on web server configuration.Additionally, Django requires you to explicitly enable support for the
X-Forwarded-Host
header (via theUSE_X_FORWARDED_HOST
setting) if your configuration requires it.Session security¶
会话安全
Similar to the CSRF limitations requiring a site to be deployed such that untrusted users don’t have access to any subdomains,
django.contrib.sessions
also has limitations. See the session topic guide section on security for details.User-uploaded content¶
用户上传内容
Note
Consider serving static files from a cloud service or CDN to avoid some of these issues.
If your site accepts file uploads, it is strongly advised that you limit these uploads in your Web server configuration to a reasonable size in order to prevent denial of service (DOS) attacks. In Apache, this can be easily set using theLimitRequestBody directive.
If you are serving your own static files, be sure that handlers like Apache’s
mod_php
, which would execute static files as code, are disabled. You don’t want users to be able to execute arbitrary code by uploading and requesting a specially crafted file.Django’s media upload handling poses some vulnerabilities when that media is served in ways that do not follow security best practices. Specifically, an HTML file can be uploaded as an image if that file contains a valid PNG header followed by malicious HTML. This file will pass verification of the library that Django uses for
ImageField
image processing (Pillow). When this file is subsequently displayed to a user, it may be displayed as HTML depending on the type and configuration of your web server.No bulletproof technical solution exists at the framework level to safely validate all user uploaded file content, however, there are some other steps you can take to mitigate these attacks:
- One class of attacks can be prevented by always serving user uploaded content from a distinct top-level or second-level domain. This prevents any exploit blocked by same-origin policy protections such as cross site scripting. For example, if your site runs on
example.com
, you would want to serve uploaded content (theMEDIA_URL
setting) from something likeusercontent-example.com
. It’s not sufficient to serve content from a subdomain likeusercontent.example.com
.- Beyond this, applications may choose to define a whitelist of allowable file extensions for user uploaded files and configure the web server to only serve such files.
Additional security topics¶
附加安全话题
While Django provides good security protection out of the box, it is still important to properly deploy your application and take advantage of the security protection of the Web server, operating system and other components.
- Make sure that your Python code is outside of the Web server’s root. This will ensure that your Python code is not accidentally served as plain text (or accidentally executed).
- Take care with any user uploaded files.
- Django does not throttle requests to authenticate users. To protect against brute-force attacks against the authentication system, you may consider deploying a Django plugin or Web server module to throttle these requests.
- Keep your
SECRET_KEY
a secret.- It is a good idea to limit the accessibility of your caching system and database using a firewall.
- Take a look at the Open Web Application Security Project (OWASP) Top 10 list which identifies some common vulnerabilities in web applications. While Django has tools to address some of the issues, other issues must be accounted for in the design of your project.
1
Django : Security in Django的更多相关文章
- Django组件(三) Django之中间件
中间件概述 中间件顾名思义,是介于request与response处理之间的一道处理过程,相对比较轻量级,并且在全局上改变django的输入与输出.因为改变的是全局,所以需要谨慎实用,用不好会影响到性 ...
- Django框架(一)-Django初识
Django初识 一.Web框架本质—自己实现Web框架 1.所有的Web应用本质上就是一个socket服务端,而用户的浏览器就是一个socket客户端 import socket sk = sock ...
- Django学习笔记 Django的工程目录
mysite├── manage.py 管理项目:包括数据库建立.服务器运行.测试……└── mysite ├── __init__.py ├── settings.py 配置文件:应用 ...
- Web框架之Django_01初识(三大主流web框架、Django安装、Django项目创建方式及其相关配置、Django基础三件套:HttpResponse、render、redirect)
摘要: Web框架概述 Django简介 Django项目创建 Django基础必备三件套(HttpResponse.render.redirect) 一.Web框架概述: Python三大主流Web ...
- Django框架02 /Django下载安装、url路由分发
Django框架02 /Django下载安装.url路由分发 目录 Django框架02 /Django下载安装.url路由分发 1. django下载安装 2. pycharm创建项目 3. 基于D ...
- 五步教你实现使用Nginx+uWSGI+Django方法部署Django程序
Django的部署可以有很多方式,采用nginx+uwsgi的方式是其中比较常见的一种方式. 在这种方式中,我们的通常做法是,将nginx作为服务器最前端,它将接收WEB的所有请求,统一管理请求.ng ...
- 【Django】Django 如何使用 Django设置的日志?
代码: from django.core.management.base import BaseCommand, CommandError from django.db import models # ...
- python学习笔记--Django入门三 Django 与数据库的交互:数据建模
把数据存取逻辑.业务逻辑和表现逻辑组合在一起的概念有时被称为软件架构的 Model-View-Controller (MVC)模式.在这个模式中, Model 代表数据存取层,View 代表的是系统中 ...
- [Django高级]理解django中的中间件机制和执行顺序
原文来自 Understanding Django Middlewares, 这篇文章从整体上介绍了django中中间件定义,作用,和怎么样自己写中间件 –orangleliu. 注:middlewa ...
随机推荐
- 避免重复提交?分布式服务的幂等性设计! 架构文摘 今天 点击蓝色“架构文摘”关注我哟 加个“星标”,每天上午 09:25,干货推送! 来源:https://www.cnblogs.com/QG-whz/p/10372458.html 作者:melonstreet
避免重复提交?分布式服务的幂等性设计! 架构文摘 今天 点击蓝色"架构文摘"关注我哟 加个"星标",每天上午 09:25,干货推送! 来源:h ...
- Springboot中mybatis控制台打印sql语句
Springboot中mybatis控制台打印sql语句 https://www.jianshu.com/p/3cfe5f6e9174 https://www.jianshu.com/go-wild? ...
- Java Socket实战之七 使用Socket通信传输文件
http://blog.csdn.net/kongxx/article/details/7319410 package com.googlecode.garbagecan.test.socket.ni ...
- Java反序列化: 基于CommonsCollections4的Gadget分析 Java 序列化与反序列化安全分析
Java反序列化: 基于CommonsCollections4的Gadget分析 welkin 京东安全 5天前 https://mp.weixin.qq.com/s/OqIWUsJe9XV39SPN ...
- Java 常见关键字总结:final、static、this、super!
final,static,this,super 关键字总结 final 关键字 final关键字,意思是最终的.不可修改的,最见不得变化 ,用来修饰类.方法和变量,具有以下特点: final修饰的类不 ...
- java创建线程的多种方式
java创建线程的四种方式 1.继承 Thread 类 通过继承 Thread 类,并重写它的 run 方法,我们就可以创建一个线程. 首先定义一个类来继承 Thread 类,重写 run 方法. 然 ...
- Language Guide (proto3) | proto3 语言指南(十四)选项
Options - 选项 .proto文件中的单个声明可以使用许多 选项 进行注释.选项不会更改声明的总体含义,但可能会影响在特定上下文中处理声明的方式.可用选项的完整列表在google/protob ...
- HTTPS是怎么保证数据安全传输的?
前言 关于HTTPS的连接过程,也是老生常谈的话题了. 其中涉及到的数字证书.电子签名.SSL/TLS.对称加密.非对称加密的问题总是让人摸不清头脑,不知道怎么回答. 今天就和大家再熟悉熟悉这其中千丝 ...
- EasyConnect连接成功后,虚拟ip地位未分配
文章目录 #问题描述: 今天公司做项目,连接上EasyConnect以后,显示连接成功,但是虚拟ip地址未分配,导致无法远程连接数据库,以及svn无法更新项目. #解决办法: 百度网上各种解决办法,没 ...
- 使用Docker Registry管理Docker镜像
文章目录 使用Docker Registry管理Docker镜像 1.使用Docker Hub管理镜像 1.1注册与登录 1.2创建仓库 1.3推送镜像 2. 使用私有仓库管理镜像 2.1 搭建私有仓 ...