SlideShare ist ein Scribd-Unternehmen logo
1 von 78
Downloaden Sie, um offline zu lesen
Two Scoops of Django
Security Best Practices
Spin Lai
I. Django Configurations
II. Django Security Features
III. Django Admin
IV. What Else ?
I. Django Configurations
II. Django Security Features
III. Django Admin
IV. What Else ?
Django Configurations
Designate Settings
DEBUG / TEMPLATE_DEBUG
ALLOWED_HOSTS
SECRET_KEY
!
Django Configurations
Designate Settings
DEBUG / TEMPLATE_DEBUG
ALLOW_HOSTS
SECRET_KEY
!
$ python manage.py --settings=[setting path]
$ django-admin.py --settings=[setting path]
$ export DJANGO_SETTINGS_MODULE=[setting path]
Django Configurations
Designate Settings
DEBUG / TEMPLATE_DEBUG
ALLOWED_HOSTS
SECRET_KEY
!
DEBUG = False
!
TEMPLATE_DEBUG = False
Django Configurations
Designate Settings
DEBUG / TEMPLATE_DEBUG
ALLOWED_HOSTS
SECRET_KEY
!
# Must be set when DEBUG = False
ALLOWED_HOSTS = [
'localhost',
'www.example.com',
'.example.com',
'*' # Avoid !
]
Django Configurations
Designate Settings
DEBUG / TEMPLATE_DEBUG
ALLOWED_HOSTS
SECRET_KEY
!
‣ Configuration values, not code.
‣ DO NOT keep them in version control.
‣ Use environment variables.
Django Configurations
Designate Settings
DEBUG / TEMPLATE_DEBUG
ALLOWED_HOSTS
SECRET_KEY
!
!
def get_env_variable(varname):
try:
return os.environ[varname]
except KeyError:
msg = "Set the %s environment variable" % var_name
raise ImporperlyConfigured(msg)
I. Django Configurations
II. Django Security Features
III. Django Admin
IV. What Else ?
Django Security Features
XSS Protection
CSRF Protection
Injection Protection
Clickjacking Protection
SSL / HTTPS
Password Storage
Data Validation
Django Security Features
XSS Protection
CSRF Protection
Injection Protection
Clickjacking Protection
SSL / HTTPS
Password Storage
Data Validation
‣ Django by default escapes specific characters
‣ Be careful when using is_safe attribute
‣ Be very careful when storing HTML in Database
Django Security Features
XSS Protection
CSRF Protection
Injection Protection
Clickjacking Protection
SSL / HTTPS
Password Storage
Data Validation
CSRF protection
• Django CSRF Protection Workflow
• CSRF Protection for AJAX Request
• HTML Search Form
• CsrfViewMiddleware rather than @csrf_protect
• Be careful with @csrf_exempt
CSRF protection
• Django CSRF Protection Workflow
• CSRF Protection for AJAX Request
• HTML Search Form
• CsrfViewMiddleware rather than csrf_protect()
• Be careful with csrf_exempt()
‣ Random token value by CsrfViewMiddleware (CSRF cookie)
‣ `csrf_token` template tag generate hidden input
‣ Every request calls django.middleware.csrf.get_token()
‣ Compare CSRF cookie with `csrfmiddlewaretoken` value
‣ With HTTPS, CsrfViewMiddleWare will check referer header
CSRF protection
• Django CSRF Protection Workflow
• CSRF Protection for AJAX Request
• HTML Search Form
• CsrfViewMiddleware rather than csrf_protect()
• Be careful with csrf_exempt()
‣ Pass CSRF token as POST data with every POST request
‣ Set a custom `X-CSRFToken` header on each request
‣ CSRF cookie might not exist without `csrf_token` tag
CSRF protection
• Django CSRF Protection Workflow
• CSRF Protection for AJAX Request
• HTML Search Form
• CsrfViewMiddleware rather than csrf_protect()
• Be careful with csrf_exempt()
var origSync = Backbone.sync;
Backbone.sync = function (method, model, options) {
options.beforeSend = function (xhr) {
xhr.setRequestHeader('X-CSRFToken', $.cookie('csrftoken'));
};
!
return origSync(method, model, options);
};
CSRF protection
• Django CSRF Protection Workflow
• CSRF Protection for AJAX Request
• HTML Search Form
• CsrfViewMiddleware rather than @csrf_protect
• Be careful with @csrf_exempt
CSRF protection
• Django CSRF Protection Workflow
• CSRF Protection for AJAX Request
• HTML Search Form
• CsrfViewMiddleware rather than @csrf_protect
• Be careful with @csrf_exempt
CSRF protection
• Django CSRF Protection Workflow
• CSRF Protection for AJAX Request
• HTML Search Form
• CsrfViewMiddleware rather than @csrf_protect
• Be careful with @csrf_exempt
Django Security Features
XSS Protection
CSRF Protection
Injection Protection
Clickjacking Protection
SSL / HTTPS
Password Storage
Data Validation
Injection protection
• Script Injection
• SQL Injection
Injection protection
• Script Injection
• SQL Injection
‣Beware of the eval(), exec() and execfile()
‣DO NOT use `pickle` module to serialize/deserialize data.
‣Only use safe_load() in PyYAML
Injection protection
• Script Injection
• SQL Injection
‣ Django Queryset escape varaibles automatically
‣ Be careful to escape raw SQL properly
‣ Exercise caution when using extra()
Django Security Features
XSS Protection
CSRF Protection
Injection Protection
Clickjacking Protection
SSL / HTTPS
Password Storage
Data Validation
Clickjacking protection
• `X-Frame-Options` HTTP header
• Configurations
• @xframe_options_exempt
• Browsers Support
Clickjacking protection
• `X-Frame-Options` HTTP header
• Configurations
• @xframe_options_exempt
• Browsers Support
Whether or not a resource is allowed to load
within a frame or iframe
Clickjacking protection
• `X-Frame-Options` HTTP header
• Configurations
• @xframe_options_exempt
• Browsers Support
MIDDLEWARE_CLASSES = (
...
'django.middleware.clickjacking.XFrameOptionsMiddleware',
...
)
Clickjacking protection
• `X-Frame-Options` HTTP header
• Configurations
• @xframe_options_exempt
• Browsers Support
# Default
X_FRAME_OPTIONS = 'SAMEORIGIN'
!
X_FRAME_OPTIONS = 'DENY'
Clickjacking protection
• `X-Frame-Options` HTTP header
• Configurations
• @xframe_options_exempt
• Browsers Support
Clickjacking protection
• `X-Frame-Options` HTTP header
• Configurations
• @xframe_options_exempt
• Browsers Support
‣ Internet Explorer 8+
‣ Firefox 3.6.9+
‣ Opera 10.5+
‣ Safari 4+
‣ Chrome 4.1+
Django Security Features
XSS Protection
CSRF Protection
Injection Protection
Clickjacking Protection
SSL / HTTPS
Password Storage
Data Validation
SSL / HTTPS
• HTTPS Everywhere !
• Secure Cookies
• HSTS
• Packages
SSL / HTTPS
• HTTPS Everywhere !
• Secure Cookies
• HSTS
• Packages
‣ Web server configuration
‣ Django middleware
‣ SSL certificate from reputable source
SSL / HTTPS
• HTTPS Everywhere !
• Secure Cookies
• HSTS
• Packages
SECURE_PROXY_SSL_HEADER = False
!
$ export HTTPS=on
SSL / HTTPS
• HTTPS Everywhere !
• Secure Cookies
• HSTS
• Packages
SESSION_COOKIE_SECURE = True
!
CSRF_COOKIE_SECURE = True
SSL / HTTPS
• HTTPS Everywhere !
• Secure Cookies
• HSTS
• Packages
‣Redirect HTTP links to HTTPS
‣Web server level configuration
‣HSTS-compliant browsers
SSL / HTTPS
• HTTPS Everywhere !
• Secure Cookies
• HSTS
• Packages
Strict-Transport-Security: max-age=31536000, includeSubDomains
SSL / HTTPS
• HTTPS Everywhere !
• Secure Cookies
• HSTS
• Packages
‣ django-sslify
‣ django-secure
‣ django-hstsmiddleware
Django Security Features
XSS Protection
CSRF Protection
Injection Protection
Clickjacking Protection
SSL / HTTPS
Password Storage
Data Validation
Password Storage
• PBKDF2 + SHA256
• User.password
• PASSWORD_HASHER
• Use bcrypt
• Increase work factor
Password Storage
• PBKDF2 + SHA256
• User.password
• PASSWORD_HASHER
• Use bcrypt
• Increase work factor
Password Storage
• PBKDF2 + SHA256
• User.password
• PASSWORD_HASHER
• Use bcrypt
• Increase work factor
<algorithm>$<iteration>$<salt>$<hash>
Password Storage
• PBKDF2 + SHA256
• User.password
• PASSWORD_HASHER
• Use bcrypt
• Increase work factor
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
'django.contrib.auth.hashers.SHA1PasswordHasher',
'django.contrib.auth.hashers.MD5PasswordHasher',
'django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher',
'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher',
'django.contrib.auth.hashers.CryptPasswordHasher',
)
Password Storage
• PBKDF2 + SHA256
• User.password
• PASSWORD_HASHER
• bcrypt
• Increase work factor
Password Storage
• PBKDF2 + SHA256
• User.password
• PASSWORD_HASHER
• Use bcrypt
• Increase work factor
Django Security Features
XSS Protection
CSRF Protection
Injection Protection
Clickjacking Protection
SSL / HTTPS
Password Storage
Data Validation
Data Validation
• Django Forms
• User-Uploaded Content
Data Validation
• Django Forms
• User-Uploaded Content
‣ Designed to validate Python dictionaries
‣ Not only for HTTP POST request
‣ DO NOT use ModelForms.Meta.exclude
‣ Use ModelForms.Meta.fields instead
Data Validation
• Django Forms
• User-Uploaded Content
from django import forms
from .models import Store
!
class StoreForm(forms.ModelForm):
!
class Meta:
model = Store
# Don't Do this!!
excludes = ("pk", "slug", "modified")
Data Validation
• Django Forms
• User-Uploaded Content
from django import forms
from .models import Store
!
class StoreForm(forms.ModelForm):
!
class Meta:
model = Store
# Explicitly specifying what we want
fields = ("title", "address", "email")
Data Validation
• Django Forms
• User-Uploaded Content
‣ Limit upload in web server
‣ FileField / ImageField
‣ python-magic
‣ Validate with specific file type library
Data Validation
• Django Forms
• User-Uploaded Content
from django.utils.image import Image
!
try:
Image.open(file).verify()
except Exception:
# Pillow (or PIL) doesn't recognize it as an image.
six.reraise(ValidationError, ValidationError(
self.error_messages['invalid_image'],
code='invalid_image',
), sys.exc_info()[2])
I. Django Configurations
II. Django Security Features
III. Django Admin
IV. What Else ?
Django Admin
Change the Default Admin URL
Access Admin via HTTPS
Limited Access Based on IP
Use `allow_tags` attribute with Caution
Admin Docs
Packages
Django Admin
Change the Default Admin URL
Access Admin via HTTPS
Limited Access Based on IP
Use `allow_tags` attribute with Caution
Admin Docs
Packages
Django Admin
Change the Default Admin URL
Access Admin via HTTPS
Limited Access Based on IP
Use `allow_tags` attribute with Caution
Admin Docs
Packages
Django Admin
Change the Default Admin URL
Access Admin via HTTPS
Limited Access Based on IP
Use `allow_tags` attribute with Caution
Admin Docs
Packages
‣ Web server configuration
‣ Django middleware
Django Admin
Change the Default Admin URL
Access Admin via HTTPS
Limited Access Based on IP
Use `allow_tags` attribute with Caution
Admin Docs
Packages
Django Admin
Change the Default Admin URL
Access Admin via HTTPS
Limited Access Based on IP
Use `allow_tags` attribute with Caution
Admin Docs
Packages
Django Admin
Change the Default Admin URL
Access Admin via HTTPS
Limited Access Based on IP
Use `allow_tags` attribute with Caution
Admin Docs
Packages
‣ django-admin-honeypot
‣ django-axes
I. Django Configurations
II. Django Security Features
III. Django Admin
IV. What Else ?
What else ?
Harden your servers
NEVER store credit card data
Server monitoring
Vulnerability reporting page
Keep things up-to-date
What else ?
Harden your servers
NEVER store credit card data
Server monitoring
Vulnerability reporting page
Keep things up-to-date
What else ?
Harden your servers
NEVER store credit card data
Server monitoring
Vulnerability reporting page
Keep things up-to-date
‣ PCI-DSS Security Standards
‣ Sufficient Time/Resource/Funds
‣ Using 3rd-Party Services
‣ Beware of Open Source Solutions
What else ?
Harden your servers
NEVER store credit card data
Server monitoring
Vulnerability reporting page
Keep things up-to-date
‣ Check access/error logs regularly
‣ Install monitoring tools
What else ?
Harden your servers
NEVER store credit card data
Server monitoring
Vulnerability reporting page
Keep things up-to-date
What else ?
Harden your servers
NEVER store credit card data
Server monitoring
Vulnerability reporting page
Keep things up-to-date
What else ?
Harden your servers
NEVER store credit card data
Server monitoring
Vulnerability reporting page
Keep things up-to-date
What else ?
Harden your servers
NEVER store credit card data
Server monitoring
Vulnerability reporting page
Keep things up-to-date
What else ?
Harden your servers
NEVER store credit card data
Server monitoring
Vulnerability reporting page
Keep things up-to-date
Keep Things Up-to-Date
• Dependencies
• Security Practices
Keep Things Up-to-Date
• Dependencies
• Security Practiceshttps://www.djangoproject.com/weblog/
Keep Things Up-to-Date
• Dependencies
• Security Practices
Keep Things Up-to-Date
• Dependencies
• Security Practices
Keep Things Up-to-Date
• Dependencies
• Security Practices
Thank You

Weitere ähnliche Inhalte

Was ist angesagt?

Case Study of Django: Web Frameworks that are Secure by Default
Case Study of Django: Web Frameworks that are Secure by DefaultCase Study of Django: Web Frameworks that are Secure by Default
Case Study of Django: Web Frameworks that are Secure by DefaultMohammed ALDOUB
 
Waf bypassing Techniques
Waf bypassing TechniquesWaf bypassing Techniques
Waf bypassing TechniquesAvinash Thapa
 
XSS - Do you know EVERYTHING?
XSS - Do you know EVERYTHING?XSS - Do you know EVERYTHING?
XSS - Do you know EVERYTHING?Yurii Bilyk
 
Time based CAPTCHA protected SQL injection through SOAP-webservice
Time based CAPTCHA protected SQL injection through SOAP-webserviceTime based CAPTCHA protected SQL injection through SOAP-webservice
Time based CAPTCHA protected SQL injection through SOAP-webserviceFrans Rosén
 
The Secret Life of a Bug Bounty Hunter – Frans Rosén @ Security Fest 2016
The Secret Life of a Bug Bounty Hunter – Frans Rosén @ Security Fest 2016The Secret Life of a Bug Bounty Hunter – Frans Rosén @ Security Fest 2016
The Secret Life of a Bug Bounty Hunter – Frans Rosén @ Security Fest 2016Frans Rosén
 
Attacking thru HTTP Host header
Attacking thru HTTP Host headerAttacking thru HTTP Host header
Attacking thru HTTP Host headerSergey Belov
 
Cross Site Scripting
Cross Site ScriptingCross Site Scripting
Cross Site ScriptingAli Mattash
 
XSS Magic tricks
XSS Magic tricksXSS Magic tricks
XSS Magic tricksGarethHeyes
 
Brute force-attack presentation
Brute force-attack presentationBrute force-attack presentation
Brute force-attack presentationMahmoud Ibra
 
Web Application Penetration Testing - 101
Web Application Penetration Testing - 101Web Application Penetration Testing - 101
Web Application Penetration Testing - 101Andrea Hauser
 
XXE Exposed: SQLi, XSS, XXE and XEE against Web Services
XXE Exposed: SQLi, XSS, XXE and XEE against Web ServicesXXE Exposed: SQLi, XSS, XXE and XEE against Web Services
XXE Exposed: SQLi, XSS, XXE and XEE against Web ServicesAbraham Aranguren
 
Cross site scripting
Cross site scriptingCross site scripting
Cross site scriptingkinish kumar
 
X-XSS-Nightmare: 1; mode=attack XSS Attacks Exploiting XSS Filter
X-XSS-Nightmare: 1; mode=attack XSS Attacks Exploiting XSS FilterX-XSS-Nightmare: 1; mode=attack XSS Attacks Exploiting XSS Filter
X-XSS-Nightmare: 1; mode=attack XSS Attacks Exploiting XSS FilterMasato Kinugawa
 
How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...
How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...
How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...bugcrowd
 
Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...Codemotion
 

Was ist angesagt? (20)

Bug Bounty for - Beginners
Bug Bounty for - BeginnersBug Bounty for - Beginners
Bug Bounty for - Beginners
 
Case Study of Django: Web Frameworks that are Secure by Default
Case Study of Django: Web Frameworks that are Secure by DefaultCase Study of Django: Web Frameworks that are Secure by Default
Case Study of Django: Web Frameworks that are Secure by Default
 
Waf bypassing Techniques
Waf bypassing TechniquesWaf bypassing Techniques
Waf bypassing Techniques
 
XSS - Do you know EVERYTHING?
XSS - Do you know EVERYTHING?XSS - Do you know EVERYTHING?
XSS - Do you know EVERYTHING?
 
Time based CAPTCHA protected SQL injection through SOAP-webservice
Time based CAPTCHA protected SQL injection through SOAP-webserviceTime based CAPTCHA protected SQL injection through SOAP-webservice
Time based CAPTCHA protected SQL injection through SOAP-webservice
 
The Secret Life of a Bug Bounty Hunter – Frans Rosén @ Security Fest 2016
The Secret Life of a Bug Bounty Hunter – Frans Rosén @ Security Fest 2016The Secret Life of a Bug Bounty Hunter – Frans Rosén @ Security Fest 2016
The Secret Life of a Bug Bounty Hunter – Frans Rosén @ Security Fest 2016
 
Attacking thru HTTP Host header
Attacking thru HTTP Host headerAttacking thru HTTP Host header
Attacking thru HTTP Host header
 
Cross Site Scripting
Cross Site ScriptingCross Site Scripting
Cross Site Scripting
 
Building Advanced XSS Vectors
Building Advanced XSS VectorsBuilding Advanced XSS Vectors
Building Advanced XSS Vectors
 
XSS Magic tricks
XSS Magic tricksXSS Magic tricks
XSS Magic tricks
 
Brute force-attack presentation
Brute force-attack presentationBrute force-attack presentation
Brute force-attack presentation
 
Frans Rosén Keynote at BSides Ahmedabad
Frans Rosén Keynote at BSides AhmedabadFrans Rosén Keynote at BSides Ahmedabad
Frans Rosén Keynote at BSides Ahmedabad
 
Web Application Penetration Testing - 101
Web Application Penetration Testing - 101Web Application Penetration Testing - 101
Web Application Penetration Testing - 101
 
XXE Exposed: SQLi, XSS, XXE and XEE against Web Services
XXE Exposed: SQLi, XSS, XXE and XEE against Web ServicesXXE Exposed: SQLi, XSS, XXE and XEE against Web Services
XXE Exposed: SQLi, XSS, XXE and XEE against Web Services
 
Cross site scripting
Cross site scriptingCross site scripting
Cross site scripting
 
X-XSS-Nightmare: 1; mode=attack XSS Attacks Exploiting XSS Filter
X-XSS-Nightmare: 1; mode=attack XSS Attacks Exploiting XSS FilterX-XSS-Nightmare: 1; mode=attack XSS Attacks Exploiting XSS Filter
X-XSS-Nightmare: 1; mode=attack XSS Attacks Exploiting XSS Filter
 
How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...
How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...
How to Shot Web - Jason Haddix at DEFCON 23 - See it Live: Details in Descrip...
 
XSS
XSSXSS
XSS
 
Api security-testing
Api security-testingApi security-testing
Api security-testing
 
Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...
 

Andere mochten auch

12 tips on Django Best Practices
12 tips on Django Best Practices12 tips on Django Best Practices
12 tips on Django Best PracticesDavid Arcos
 
A quick python_tour
A quick python_tourA quick python_tour
A quick python_tourcghtkh
 
Outside-In Development With Cucumber
Outside-In Development With CucumberOutside-In Development With Cucumber
Outside-In Development With CucumberBen Mabey
 
Make It Cooler: Using Decentralized Version Control
Make It Cooler: Using Decentralized Version ControlMake It Cooler: Using Decentralized Version Control
Make It Cooler: Using Decentralized Version Controlindiver
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Jacob Kaplan-Moss
 
Prepare for JDK 9
Prepare for JDK 9Prepare for JDK 9
Prepare for JDK 9haochenglee
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJames Casey
 
Introduction to Git for developers
Introduction to Git for developersIntroduction to Git for developers
Introduction to Git for developersDmitry Guyvoronsky
 
Flask and Paramiko for Python VA
Flask and Paramiko for Python VAFlask and Paramiko for Python VA
Flask and Paramiko for Python VAEnrique Valenzuela
 
Django rest framework in 20 minuten
Django rest framework in 20 minutenDjango rest framework in 20 minuten
Django rest framework in 20 minutenAndi Albrecht
 
Django deployment best practices
Django deployment best practicesDjango deployment best practices
Django deployment best practicesErik LaBianca
 
Do more than one thing at the same time, the Python way
Do more than one thing at the same time, the Python wayDo more than one thing at the same time, the Python way
Do more than one thing at the same time, the Python wayJaime Buelta
 
Towards Continuous Deployment with Django
Towards Continuous Deployment with DjangoTowards Continuous Deployment with Django
Towards Continuous Deployment with DjangoRoger Barnes
 
Pythonic Deployment with Fabric 0.9
Pythonic Deployment with Fabric 0.9Pythonic Deployment with Fabric 0.9
Pythonic Deployment with Fabric 0.9Corey Oordt
 
Django REST Framework
Django REST FrameworkDjango REST Framework
Django REST FrameworkLoad Impact
 
The WHY behind TDD/BDD and the HOW with RSpec
The WHY behind TDD/BDD and the HOW with RSpecThe WHY behind TDD/BDD and the HOW with RSpec
The WHY behind TDD/BDD and the HOW with RSpecBen Mabey
 
Building a platform with Django, Docker, and Salt
Building a platform with Django, Docker, and SaltBuilding a platform with Django, Docker, and Salt
Building a platform with Django, Docker, and Saltbaremetal
 

Andere mochten auch (20)

Django In The Real World
Django In The Real WorldDjango In The Real World
Django In The Real World
 
12 tips on Django Best Practices
12 tips on Django Best Practices12 tips on Django Best Practices
12 tips on Django Best Practices
 
A quick python_tour
A quick python_tourA quick python_tour
A quick python_tour
 
Capybara
CapybaraCapybara
Capybara
 
Outside-In Development With Cucumber
Outside-In Development With CucumberOutside-In Development With Cucumber
Outside-In Development With Cucumber
 
Make It Cooler: Using Decentralized Version Control
Make It Cooler: Using Decentralized Version ControlMake It Cooler: Using Decentralized Version Control
Make It Cooler: Using Decentralized Version Control
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)
 
Prepare for JDK 9
Prepare for JDK 9Prepare for JDK 9
Prepare for JDK 9
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Introduction to Git for developers
Introduction to Git for developersIntroduction to Git for developers
Introduction to Git for developers
 
Flask and Paramiko for Python VA
Flask and Paramiko for Python VAFlask and Paramiko for Python VA
Flask and Paramiko for Python VA
 
Django rest framework in 20 minuten
Django rest framework in 20 minutenDjango rest framework in 20 minuten
Django rest framework in 20 minuten
 
Django deployment best practices
Django deployment best practicesDjango deployment best practices
Django deployment best practices
 
Ansible on AWS
Ansible on AWSAnsible on AWS
Ansible on AWS
 
Do more than one thing at the same time, the Python way
Do more than one thing at the same time, the Python wayDo more than one thing at the same time, the Python way
Do more than one thing at the same time, the Python way
 
Towards Continuous Deployment with Django
Towards Continuous Deployment with DjangoTowards Continuous Deployment with Django
Towards Continuous Deployment with Django
 
Pythonic Deployment with Fabric 0.9
Pythonic Deployment with Fabric 0.9Pythonic Deployment with Fabric 0.9
Pythonic Deployment with Fabric 0.9
 
Django REST Framework
Django REST FrameworkDjango REST Framework
Django REST Framework
 
The WHY behind TDD/BDD and the HOW with RSpec
The WHY behind TDD/BDD and the HOW with RSpecThe WHY behind TDD/BDD and the HOW with RSpec
The WHY behind TDD/BDD and the HOW with RSpec
 
Building a platform with Django, Docker, and Salt
Building a platform with Django, Docker, and SaltBuilding a platform with Django, Docker, and Salt
Building a platform with Django, Docker, and Salt
 

Ähnlich wie Two scoops of Django - Security Best Practices

PHP SA 2014 - Releasing Your Open Source Project
PHP SA 2014 - Releasing Your Open Source ProjectPHP SA 2014 - Releasing Your Open Source Project
PHP SA 2014 - Releasing Your Open Source Projectxsist10
 
20160905 - BrisJS - nightwatch testing
20160905 - BrisJS - nightwatch testing20160905 - BrisJS - nightwatch testing
20160905 - BrisJS - nightwatch testingVladimir Roudakov
 
Things Your Mother Didnt Tell You About Bundle Configurations - Symfony Live…
Things Your Mother Didnt Tell You About Bundle Configurations - Symfony Live…Things Your Mother Didnt Tell You About Bundle Configurations - Symfony Live…
Things Your Mother Didnt Tell You About Bundle Configurations - Symfony Live…D
 
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...D
 
Hadoop Security Now and Future
Hadoop Security Now and FutureHadoop Security Now and Future
Hadoop Security Now and Futuretcloudcomputing-tw
 
What mom never told you about bundle configurations - Symfony Live Paris 2012
What mom never told you about bundle configurations - Symfony Live Paris 2012What mom never told you about bundle configurations - Symfony Live Paris 2012
What mom never told you about bundle configurations - Symfony Live Paris 2012D
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony TechniquesKris Wallsmith
 
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.pptLecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.pptSreejithVP7
 
HTTP Caching and PHP
HTTP Caching and PHPHTTP Caching and PHP
HTTP Caching and PHPDavid de Boer
 
Resource Registries: Plone Conference 2014
Resource Registries: Plone Conference 2014Resource Registries: Plone Conference 2014
Resource Registries: Plone Conference 2014Rob Gietema
 
Talk about html5 security
Talk about html5 securityTalk about html5 security
Talk about html5 securityHuang Toby
 
Resource registries plone conf 2014
Resource registries plone conf 2014Resource registries plone conf 2014
Resource registries plone conf 2014Ramon Navarro
 
OWASP Top 10 at International PHP Conference 2014 in Berlin
OWASP Top 10 at International PHP Conference 2014 in BerlinOWASP Top 10 at International PHP Conference 2014 in Berlin
OWASP Top 10 at International PHP Conference 2014 in BerlinTobias Zander
 
(SDD402) Amazon ElastiCache Deep Dive | AWS re:Invent 2014
(SDD402) Amazon ElastiCache Deep Dive | AWS re:Invent 2014(SDD402) Amazon ElastiCache Deep Dive | AWS re:Invent 2014
(SDD402) Amazon ElastiCache Deep Dive | AWS re:Invent 2014Amazon Web Services
 
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQ
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQUA testing with Selenium and PHPUnit - PHPBenelux Summer BBQ
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQMichelangelo van Dam
 
ACL in CodeIgniter
ACL in CodeIgniterACL in CodeIgniter
ACL in CodeIgnitermirahman
 

Ähnlich wie Two scoops of Django - Security Best Practices (20)

Django cryptography
Django cryptographyDjango cryptography
Django cryptography
 
PHP SA 2014 - Releasing Your Open Source Project
PHP SA 2014 - Releasing Your Open Source ProjectPHP SA 2014 - Releasing Your Open Source Project
PHP SA 2014 - Releasing Your Open Source Project
 
20160905 - BrisJS - nightwatch testing
20160905 - BrisJS - nightwatch testing20160905 - BrisJS - nightwatch testing
20160905 - BrisJS - nightwatch testing
 
Things Your Mother Didnt Tell You About Bundle Configurations - Symfony Live…
Things Your Mother Didnt Tell You About Bundle Configurations - Symfony Live…Things Your Mother Didnt Tell You About Bundle Configurations - Symfony Live…
Things Your Mother Didnt Tell You About Bundle Configurations - Symfony Live…
 
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...
 
Hadoop Security Now and Future
Hadoop Security Now and FutureHadoop Security Now and Future
Hadoop Security Now and Future
 
What mom never told you about bundle configurations - Symfony Live Paris 2012
What mom never told you about bundle configurations - Symfony Live Paris 2012What mom never told you about bundle configurations - Symfony Live Paris 2012
What mom never told you about bundle configurations - Symfony Live Paris 2012
 
Blog Hacks 2011
Blog Hacks 2011Blog Hacks 2011
Blog Hacks 2011
 
Web security
Web securityWeb security
Web security
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.pptLecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
 
Rails Security
Rails SecurityRails Security
Rails Security
 
HTTP Caching and PHP
HTTP Caching and PHPHTTP Caching and PHP
HTTP Caching and PHP
 
Resource Registries: Plone Conference 2014
Resource Registries: Plone Conference 2014Resource Registries: Plone Conference 2014
Resource Registries: Plone Conference 2014
 
Talk about html5 security
Talk about html5 securityTalk about html5 security
Talk about html5 security
 
Resource registries plone conf 2014
Resource registries plone conf 2014Resource registries plone conf 2014
Resource registries plone conf 2014
 
OWASP Top 10 at International PHP Conference 2014 in Berlin
OWASP Top 10 at International PHP Conference 2014 in BerlinOWASP Top 10 at International PHP Conference 2014 in Berlin
OWASP Top 10 at International PHP Conference 2014 in Berlin
 
(SDD402) Amazon ElastiCache Deep Dive | AWS re:Invent 2014
(SDD402) Amazon ElastiCache Deep Dive | AWS re:Invent 2014(SDD402) Amazon ElastiCache Deep Dive | AWS re:Invent 2014
(SDD402) Amazon ElastiCache Deep Dive | AWS re:Invent 2014
 
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQ
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQUA testing with Selenium and PHPUnit - PHPBenelux Summer BBQ
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQ
 
ACL in CodeIgniter
ACL in CodeIgniterACL in CodeIgniter
ACL in CodeIgniter
 

Mehr von Spin Lai

Django User Management & Social Authentication
Django User Management & Social AuthenticationDjango User Management & Social Authentication
Django User Management & Social AuthenticationSpin Lai
 
Django class based views for beginners
Django class based views for beginnersDjango class based views for beginners
Django class based views for beginnersSpin Lai
 
Bdd for legacy system
Bdd for legacy systemBdd for legacy system
Bdd for legacy systemSpin Lai
 
Speed up your web development
Speed up your web developmentSpeed up your web development
Speed up your web developmentSpin Lai
 
Hitcon2013 overview
Hitcon2013 overviewHitcon2013 overview
Hitcon2013 overviewSpin Lai
 
The django book - Chap10 : Advanced Models
The django book - Chap10 : Advanced ModelsThe django book - Chap10 : Advanced Models
The django book - Chap10 : Advanced ModelsSpin Lai
 

Mehr von Spin Lai (6)

Django User Management & Social Authentication
Django User Management & Social AuthenticationDjango User Management & Social Authentication
Django User Management & Social Authentication
 
Django class based views for beginners
Django class based views for beginnersDjango class based views for beginners
Django class based views for beginners
 
Bdd for legacy system
Bdd for legacy systemBdd for legacy system
Bdd for legacy system
 
Speed up your web development
Speed up your web developmentSpeed up your web development
Speed up your web development
 
Hitcon2013 overview
Hitcon2013 overviewHitcon2013 overview
Hitcon2013 overview
 
The django book - Chap10 : Advanced Models
The django book - Chap10 : Advanced ModelsThe django book - Chap10 : Advanced Models
The django book - Chap10 : Advanced Models
 

Kürzlich hochgeladen

VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profileakrivarotava
 

Kürzlich hochgeladen (20)

VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profile
 

Two scoops of Django - Security Best Practices

  • 1. Two Scoops of Django Security Best Practices Spin Lai
  • 2.
  • 3. I. Django Configurations II. Django Security Features III. Django Admin IV. What Else ?
  • 4. I. Django Configurations II. Django Security Features III. Django Admin IV. What Else ?
  • 5. Django Configurations Designate Settings DEBUG / TEMPLATE_DEBUG ALLOWED_HOSTS SECRET_KEY !
  • 6. Django Configurations Designate Settings DEBUG / TEMPLATE_DEBUG ALLOW_HOSTS SECRET_KEY ! $ python manage.py --settings=[setting path] $ django-admin.py --settings=[setting path] $ export DJANGO_SETTINGS_MODULE=[setting path]
  • 7. Django Configurations Designate Settings DEBUG / TEMPLATE_DEBUG ALLOWED_HOSTS SECRET_KEY ! DEBUG = False ! TEMPLATE_DEBUG = False
  • 8. Django Configurations Designate Settings DEBUG / TEMPLATE_DEBUG ALLOWED_HOSTS SECRET_KEY ! # Must be set when DEBUG = False ALLOWED_HOSTS = [ 'localhost', 'www.example.com', '.example.com', '*' # Avoid ! ]
  • 9. Django Configurations Designate Settings DEBUG / TEMPLATE_DEBUG ALLOWED_HOSTS SECRET_KEY ! ‣ Configuration values, not code. ‣ DO NOT keep them in version control. ‣ Use environment variables.
  • 10. Django Configurations Designate Settings DEBUG / TEMPLATE_DEBUG ALLOWED_HOSTS SECRET_KEY ! ! def get_env_variable(varname): try: return os.environ[varname] except KeyError: msg = "Set the %s environment variable" % var_name raise ImporperlyConfigured(msg)
  • 11. I. Django Configurations II. Django Security Features III. Django Admin IV. What Else ?
  • 12. Django Security Features XSS Protection CSRF Protection Injection Protection Clickjacking Protection SSL / HTTPS Password Storage Data Validation
  • 13. Django Security Features XSS Protection CSRF Protection Injection Protection Clickjacking Protection SSL / HTTPS Password Storage Data Validation ‣ Django by default escapes specific characters ‣ Be careful when using is_safe attribute ‣ Be very careful when storing HTML in Database
  • 14. Django Security Features XSS Protection CSRF Protection Injection Protection Clickjacking Protection SSL / HTTPS Password Storage Data Validation
  • 15. CSRF protection • Django CSRF Protection Workflow • CSRF Protection for AJAX Request • HTML Search Form • CsrfViewMiddleware rather than @csrf_protect • Be careful with @csrf_exempt
  • 16. CSRF protection • Django CSRF Protection Workflow • CSRF Protection for AJAX Request • HTML Search Form • CsrfViewMiddleware rather than csrf_protect() • Be careful with csrf_exempt() ‣ Random token value by CsrfViewMiddleware (CSRF cookie) ‣ `csrf_token` template tag generate hidden input ‣ Every request calls django.middleware.csrf.get_token() ‣ Compare CSRF cookie with `csrfmiddlewaretoken` value ‣ With HTTPS, CsrfViewMiddleWare will check referer header
  • 17. CSRF protection • Django CSRF Protection Workflow • CSRF Protection for AJAX Request • HTML Search Form • CsrfViewMiddleware rather than csrf_protect() • Be careful with csrf_exempt() ‣ Pass CSRF token as POST data with every POST request ‣ Set a custom `X-CSRFToken` header on each request ‣ CSRF cookie might not exist without `csrf_token` tag
  • 18. CSRF protection • Django CSRF Protection Workflow • CSRF Protection for AJAX Request • HTML Search Form • CsrfViewMiddleware rather than csrf_protect() • Be careful with csrf_exempt() var origSync = Backbone.sync; Backbone.sync = function (method, model, options) { options.beforeSend = function (xhr) { xhr.setRequestHeader('X-CSRFToken', $.cookie('csrftoken')); }; ! return origSync(method, model, options); };
  • 19. CSRF protection • Django CSRF Protection Workflow • CSRF Protection for AJAX Request • HTML Search Form • CsrfViewMiddleware rather than @csrf_protect • Be careful with @csrf_exempt
  • 20. CSRF protection • Django CSRF Protection Workflow • CSRF Protection for AJAX Request • HTML Search Form • CsrfViewMiddleware rather than @csrf_protect • Be careful with @csrf_exempt
  • 21. CSRF protection • Django CSRF Protection Workflow • CSRF Protection for AJAX Request • HTML Search Form • CsrfViewMiddleware rather than @csrf_protect • Be careful with @csrf_exempt
  • 22. Django Security Features XSS Protection CSRF Protection Injection Protection Clickjacking Protection SSL / HTTPS Password Storage Data Validation
  • 23. Injection protection • Script Injection • SQL Injection
  • 24. Injection protection • Script Injection • SQL Injection ‣Beware of the eval(), exec() and execfile() ‣DO NOT use `pickle` module to serialize/deserialize data. ‣Only use safe_load() in PyYAML
  • 25. Injection protection • Script Injection • SQL Injection ‣ Django Queryset escape varaibles automatically ‣ Be careful to escape raw SQL properly ‣ Exercise caution when using extra()
  • 26. Django Security Features XSS Protection CSRF Protection Injection Protection Clickjacking Protection SSL / HTTPS Password Storage Data Validation
  • 27. Clickjacking protection • `X-Frame-Options` HTTP header • Configurations • @xframe_options_exempt • Browsers Support
  • 28. Clickjacking protection • `X-Frame-Options` HTTP header • Configurations • @xframe_options_exempt • Browsers Support Whether or not a resource is allowed to load within a frame or iframe
  • 29. Clickjacking protection • `X-Frame-Options` HTTP header • Configurations • @xframe_options_exempt • Browsers Support MIDDLEWARE_CLASSES = ( ... 'django.middleware.clickjacking.XFrameOptionsMiddleware', ... )
  • 30. Clickjacking protection • `X-Frame-Options` HTTP header • Configurations • @xframe_options_exempt • Browsers Support # Default X_FRAME_OPTIONS = 'SAMEORIGIN' ! X_FRAME_OPTIONS = 'DENY'
  • 31. Clickjacking protection • `X-Frame-Options` HTTP header • Configurations • @xframe_options_exempt • Browsers Support
  • 32. Clickjacking protection • `X-Frame-Options` HTTP header • Configurations • @xframe_options_exempt • Browsers Support ‣ Internet Explorer 8+ ‣ Firefox 3.6.9+ ‣ Opera 10.5+ ‣ Safari 4+ ‣ Chrome 4.1+
  • 33. Django Security Features XSS Protection CSRF Protection Injection Protection Clickjacking Protection SSL / HTTPS Password Storage Data Validation
  • 34. SSL / HTTPS • HTTPS Everywhere ! • Secure Cookies • HSTS • Packages
  • 35. SSL / HTTPS • HTTPS Everywhere ! • Secure Cookies • HSTS • Packages ‣ Web server configuration ‣ Django middleware ‣ SSL certificate from reputable source
  • 36. SSL / HTTPS • HTTPS Everywhere ! • Secure Cookies • HSTS • Packages SECURE_PROXY_SSL_HEADER = False ! $ export HTTPS=on
  • 37. SSL / HTTPS • HTTPS Everywhere ! • Secure Cookies • HSTS • Packages SESSION_COOKIE_SECURE = True ! CSRF_COOKIE_SECURE = True
  • 38. SSL / HTTPS • HTTPS Everywhere ! • Secure Cookies • HSTS • Packages ‣Redirect HTTP links to HTTPS ‣Web server level configuration ‣HSTS-compliant browsers
  • 39. SSL / HTTPS • HTTPS Everywhere ! • Secure Cookies • HSTS • Packages Strict-Transport-Security: max-age=31536000, includeSubDomains
  • 40. SSL / HTTPS • HTTPS Everywhere ! • Secure Cookies • HSTS • Packages ‣ django-sslify ‣ django-secure ‣ django-hstsmiddleware
  • 41. Django Security Features XSS Protection CSRF Protection Injection Protection Clickjacking Protection SSL / HTTPS Password Storage Data Validation
  • 42. Password Storage • PBKDF2 + SHA256 • User.password • PASSWORD_HASHER • Use bcrypt • Increase work factor
  • 43. Password Storage • PBKDF2 + SHA256 • User.password • PASSWORD_HASHER • Use bcrypt • Increase work factor
  • 44. Password Storage • PBKDF2 + SHA256 • User.password • PASSWORD_HASHER • Use bcrypt • Increase work factor <algorithm>$<iteration>$<salt>$<hash>
  • 45. Password Storage • PBKDF2 + SHA256 • User.password • PASSWORD_HASHER • Use bcrypt • Increase work factor PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', 'django.contrib.auth.hashers.SHA1PasswordHasher', 'django.contrib.auth.hashers.MD5PasswordHasher', 'django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher', 'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher', 'django.contrib.auth.hashers.CryptPasswordHasher', )
  • 46. Password Storage • PBKDF2 + SHA256 • User.password • PASSWORD_HASHER • bcrypt • Increase work factor
  • 47. Password Storage • PBKDF2 + SHA256 • User.password • PASSWORD_HASHER • Use bcrypt • Increase work factor
  • 48. Django Security Features XSS Protection CSRF Protection Injection Protection Clickjacking Protection SSL / HTTPS Password Storage Data Validation
  • 49. Data Validation • Django Forms • User-Uploaded Content
  • 50. Data Validation • Django Forms • User-Uploaded Content ‣ Designed to validate Python dictionaries ‣ Not only for HTTP POST request ‣ DO NOT use ModelForms.Meta.exclude ‣ Use ModelForms.Meta.fields instead
  • 51. Data Validation • Django Forms • User-Uploaded Content from django import forms from .models import Store ! class StoreForm(forms.ModelForm): ! class Meta: model = Store # Don't Do this!! excludes = ("pk", "slug", "modified")
  • 52. Data Validation • Django Forms • User-Uploaded Content from django import forms from .models import Store ! class StoreForm(forms.ModelForm): ! class Meta: model = Store # Explicitly specifying what we want fields = ("title", "address", "email")
  • 53. Data Validation • Django Forms • User-Uploaded Content ‣ Limit upload in web server ‣ FileField / ImageField ‣ python-magic ‣ Validate with specific file type library
  • 54. Data Validation • Django Forms • User-Uploaded Content from django.utils.image import Image ! try: Image.open(file).verify() except Exception: # Pillow (or PIL) doesn't recognize it as an image. six.reraise(ValidationError, ValidationError( self.error_messages['invalid_image'], code='invalid_image', ), sys.exc_info()[2])
  • 55. I. Django Configurations II. Django Security Features III. Django Admin IV. What Else ?
  • 56. Django Admin Change the Default Admin URL Access Admin via HTTPS Limited Access Based on IP Use `allow_tags` attribute with Caution Admin Docs Packages
  • 57. Django Admin Change the Default Admin URL Access Admin via HTTPS Limited Access Based on IP Use `allow_tags` attribute with Caution Admin Docs Packages
  • 58. Django Admin Change the Default Admin URL Access Admin via HTTPS Limited Access Based on IP Use `allow_tags` attribute with Caution Admin Docs Packages
  • 59. Django Admin Change the Default Admin URL Access Admin via HTTPS Limited Access Based on IP Use `allow_tags` attribute with Caution Admin Docs Packages ‣ Web server configuration ‣ Django middleware
  • 60. Django Admin Change the Default Admin URL Access Admin via HTTPS Limited Access Based on IP Use `allow_tags` attribute with Caution Admin Docs Packages
  • 61. Django Admin Change the Default Admin URL Access Admin via HTTPS Limited Access Based on IP Use `allow_tags` attribute with Caution Admin Docs Packages
  • 62. Django Admin Change the Default Admin URL Access Admin via HTTPS Limited Access Based on IP Use `allow_tags` attribute with Caution Admin Docs Packages ‣ django-admin-honeypot ‣ django-axes
  • 63. I. Django Configurations II. Django Security Features III. Django Admin IV. What Else ?
  • 64. What else ? Harden your servers NEVER store credit card data Server monitoring Vulnerability reporting page Keep things up-to-date
  • 65. What else ? Harden your servers NEVER store credit card data Server monitoring Vulnerability reporting page Keep things up-to-date
  • 66. What else ? Harden your servers NEVER store credit card data Server monitoring Vulnerability reporting page Keep things up-to-date ‣ PCI-DSS Security Standards ‣ Sufficient Time/Resource/Funds ‣ Using 3rd-Party Services ‣ Beware of Open Source Solutions
  • 67. What else ? Harden your servers NEVER store credit card data Server monitoring Vulnerability reporting page Keep things up-to-date ‣ Check access/error logs regularly ‣ Install monitoring tools
  • 68. What else ? Harden your servers NEVER store credit card data Server monitoring Vulnerability reporting page Keep things up-to-date
  • 69. What else ? Harden your servers NEVER store credit card data Server monitoring Vulnerability reporting page Keep things up-to-date
  • 70. What else ? Harden your servers NEVER store credit card data Server monitoring Vulnerability reporting page Keep things up-to-date
  • 71. What else ? Harden your servers NEVER store credit card data Server monitoring Vulnerability reporting page Keep things up-to-date
  • 72. What else ? Harden your servers NEVER store credit card data Server monitoring Vulnerability reporting page Keep things up-to-date
  • 73. Keep Things Up-to-Date • Dependencies • Security Practices
  • 74. Keep Things Up-to-Date • Dependencies • Security Practiceshttps://www.djangoproject.com/weblog/
  • 75. Keep Things Up-to-Date • Dependencies • Security Practices
  • 76. Keep Things Up-to-Date • Dependencies • Security Practices
  • 77. Keep Things Up-to-Date • Dependencies • Security Practices