SlideShare una empresa de Scribd logo
1 de 78
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

HTTP Parameter Pollution Vulnerabilities in Web Applications (Black Hat EU 2011)
HTTP Parameter Pollution Vulnerabilities in Web Applications (Black Hat EU 2011)HTTP Parameter Pollution Vulnerabilities in Web Applications (Black Hat EU 2011)
HTTP Parameter Pollution Vulnerabilities in Web Applications (Black Hat EU 2011)
Marco Balduzzi
 
Intrusion detection and prevention system for network using Honey pots and Ho...
Intrusion detection and prevention system for network using Honey pots and Ho...Intrusion detection and prevention system for network using Honey pots and Ho...
Intrusion detection and prevention system for network using Honey pots and Ho...
Eng. Mohammed Ahmed Siddiqui
 
Network Analysis Mini Project 2.pdf
Network Analysis Mini Project 2.pdfNetwork Analysis Mini Project 2.pdf
Network Analysis Mini Project 2.pdf
talkaton
 

La actualidad más candente (20)

Web application vulnerabilities
Web application vulnerabilitiesWeb application vulnerabilities
Web application vulnerabilities
 
Bettercap
BettercapBettercap
Bettercap
 
XXE - XML External Entity Attack
XXE - XML External Entity Attack	XXE - XML External Entity Attack
XXE - XML External Entity Attack
 
HTTP Parameter Pollution Vulnerabilities in Web Applications (Black Hat EU 2011)
HTTP Parameter Pollution Vulnerabilities in Web Applications (Black Hat EU 2011)HTTP Parameter Pollution Vulnerabilities in Web Applications (Black Hat EU 2011)
HTTP Parameter Pollution Vulnerabilities in Web Applications (Black Hat EU 2011)
 
Reconnaissance and Social Engineering
Reconnaissance and Social EngineeringReconnaissance and Social Engineering
Reconnaissance and Social Engineering
 
New methods for exploiting ORM injections in Java applications
New methods for exploiting ORM injections in Java applicationsNew methods for exploiting ORM injections in Java applications
New methods for exploiting ORM injections in Java applications
 
A Forgotten HTTP Invisibility Cloak
A Forgotten HTTP Invisibility CloakA Forgotten HTTP Invisibility Cloak
A Forgotten HTTP Invisibility Cloak
 
Building Advanced XSS Vectors
Building Advanced XSS VectorsBuilding Advanced XSS Vectors
Building Advanced XSS Vectors
 
OSINT: Open Source Intelligence - Rohan Braganza
OSINT: Open Source Intelligence - Rohan BraganzaOSINT: Open Source Intelligence - Rohan Braganza
OSINT: Open Source Intelligence - Rohan Braganza
 
Intrusion detection and prevention system for network using Honey pots and Ho...
Intrusion detection and prevention system for network using Honey pots and Ho...Intrusion detection and prevention system for network using Honey pots and Ho...
Intrusion detection and prevention system for network using Honey pots and Ho...
 
KKBOX WWDC17 Airplay 2 - Dolphin
KKBOX WWDC17 Airplay 2 - DolphinKKBOX WWDC17 Airplay 2 - Dolphin
KKBOX WWDC17 Airplay 2 - Dolphin
 
BGA Studio - Focus on BGA Game state machine
BGA Studio - Focus on BGA Game state machine BGA Studio - Focus on BGA Game state machine
BGA Studio - Focus on BGA Game state machine
 
Html 5 Features And Benefits
Html 5 Features And Benefits  Html 5 Features And Benefits
Html 5 Features And Benefits
 
HTTP Request and Response Structure
HTTP Request and Response StructureHTTP Request and Response Structure
HTTP Request and Response Structure
 
Petit potam slides-rtfm-ossir
Petit potam slides-rtfm-ossirPetit potam slides-rtfm-ossir
Petit potam slides-rtfm-ossir
 
Blacklist3r
Blacklist3rBlacklist3r
Blacklist3r
 
Broken access controls
Broken access controlsBroken access controls
Broken access controls
 
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...
 
Attacking thru HTTP Host header
Attacking thru HTTP Host headerAttacking thru HTTP Host header
Attacking thru HTTP Host header
 
Network Analysis Mini Project 2.pdf
Network Analysis Mini Project 2.pdfNetwork Analysis Mini Project 2.pdf
Network Analysis Mini Project 2.pdf
 

Destacado

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
 
Django deployment best practices
Django deployment best practicesDjango deployment best practices
Django deployment best practices
Erik 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 way
Jaime Buelta
 

Destacado (20)

Django In The Real World
Django In The Real WorldDjango In The Real World
Django In The Real World
 
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
 
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
 

Similar a Two scoops of Django - Security Best Practices

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
 
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
D
 

Similar a 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
 

Más de 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
 

Último

%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 

Último (20)

%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 

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