SlideShare a Scribd company logo
Two Scoops of Django
Security Best Practices
Spin Lai
Two scoops of Django - Security Best Practices
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

More Related Content

What's hot (20)

PPTX
Cross Site Scripting
Ali Mattash
 
PPTX
Html forms
Himanshu Pathak
 
PPTX
HTML Semantic Elements
Reema
 
PPT
Introduction to JavaScript (1).ppt
MuhammadRehan856177
 
PDF
HTML Head Section Elements
Somesh Gulati
 
PPTX
Django Web Application Security
levigross
 
PPTX
Jquery ppt
044249
 
PPTX
Dom based xss
Lê Giáp
 
PPTX
PHP Cookies and Sessions
Nisa Soomro
 
PPTX
Html 5
Arashdeepkaur16
 
PDF
Html,javascript & css
Predhin Sapru
 
PPTX
Electronic Circuit Style CV _ by Slidesgo.pptx
Diniyar
 
PPTX
Aligning Application Security to Compliance
Security Innovation
 
PPTX
Html Table
nehashinde41
 
PPTX
Html coding
Briana VanBuskirk
 
PPTX
DTD
Kamal Acharya
 
PDF
9- Learn CSS Fundamentals / Pseudo-classes
In a Rocket
 
PPTX
HTML CSS and Web Development
Rahul Mishra
 
PDF
HTML Dasar : #9 Tabel
Sandhika Galih
 
Cross Site Scripting
Ali Mattash
 
Html forms
Himanshu Pathak
 
HTML Semantic Elements
Reema
 
Introduction to JavaScript (1).ppt
MuhammadRehan856177
 
HTML Head Section Elements
Somesh Gulati
 
Django Web Application Security
levigross
 
Jquery ppt
044249
 
Dom based xss
Lê Giáp
 
PHP Cookies and Sessions
Nisa Soomro
 
Html,javascript & css
Predhin Sapru
 
Electronic Circuit Style CV _ by Slidesgo.pptx
Diniyar
 
Aligning Application Security to Compliance
Security Innovation
 
Html Table
nehashinde41
 
Html coding
Briana VanBuskirk
 
9- Learn CSS Fundamentals / Pseudo-classes
In a Rocket
 
HTML CSS and Web Development
Rahul Mishra
 
HTML Dasar : #9 Tabel
Sandhika Galih
 

Viewers also liked (20)

KEY
Django In The Real World
Jacob Kaplan-Moss
 
PPTX
Case Study of Django: Web Frameworks that are Secure by Default
Mohammed ALDOUB
 
PDF
12 tips on Django Best Practices
David Arcos
 
PDF
A quick python_tour
cghtkh
 
KEY
Capybara
Mona Soni
 
PDF
Outside-In Development With Cucumber
Ben Mabey
 
KEY
Make It Cooler: Using Decentralized Version Control
indiver
 
PDF
Introduction To Django (Strange Loop 2011)
Jacob Kaplan-Moss
 
PPTX
Prepare for JDK 9
haochenglee
 
KEY
Introduction to Django
James Casey
 
PPT
Introduction to Git for developers
Dmitry Guyvoronsky
 
PPTX
Flask and Paramiko for Python VA
Enrique Valenzuela
 
PDF
Django rest framework in 20 minuten
Andi Albrecht
 
PPTX
Django deployment best practices
Erik LaBianca
 
PDF
Ansible on AWS
Diego Pacheco
 
KEY
Do more than one thing at the same time, the Python way
Jaime Buelta
 
PDF
Towards Continuous Deployment with Django
Roger Barnes
 
PDF
Pythonic Deployment with Fabric 0.9
Corey Oordt
 
PDF
Django REST Framework
Load Impact
 
PDF
The WHY behind TDD/BDD and the HOW with RSpec
Ben Mabey
 
Django In The Real World
Jacob Kaplan-Moss
 
Case Study of Django: Web Frameworks that are Secure by Default
Mohammed ALDOUB
 
12 tips on Django Best Practices
David Arcos
 
A quick python_tour
cghtkh
 
Capybara
Mona Soni
 
Outside-In Development With Cucumber
Ben Mabey
 
Make It Cooler: Using Decentralized Version Control
indiver
 
Introduction To Django (Strange Loop 2011)
Jacob Kaplan-Moss
 
Prepare for JDK 9
haochenglee
 
Introduction to Django
James Casey
 
Introduction to Git for developers
Dmitry Guyvoronsky
 
Flask and Paramiko for Python VA
Enrique Valenzuela
 
Django rest framework in 20 minuten
Andi Albrecht
 
Django deployment best practices
Erik LaBianca
 
Ansible on AWS
Diego Pacheco
 
Do more than one thing at the same time, the Python way
Jaime Buelta
 
Towards Continuous Deployment with Django
Roger Barnes
 
Pythonic Deployment with Fabric 0.9
Corey Oordt
 
Django REST Framework
Load Impact
 
The WHY behind TDD/BDD and the HOW with RSpec
Ben Mabey
 
Ad

Similar to Two scoops of Django - Security Best Practices (20)

PPTX
Django cryptography
Erik LaBianca
 
PDF
PHP SA 2014 - Releasing Your Open Source Project
xsist10
 
PDF
20160905 - BrisJS - nightwatch testing
Vladimir Roudakov
 
PPT
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
pondypaiyan
 
PPTX
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...
D
 
PPTX
Things Your Mother Didnt Tell You About Bundle Configurations - Symfony Live…
D
 
PDF
Hadoop Security Now and Future
tcloudcomputing-tw
 
PPTX
What mom never told you about bundle configurations - Symfony Live Paris 2012
D
 
PDF
Blog Hacks 2011
Yusuke Wada
 
PPTX
Web security
davidahaskins
 
PDF
Advanced symfony Techniques
Kris Wallsmith
 
PPT
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
SreejithVP7
 
PDF
Rails Security
Wen-Tien Chang
 
PDF
HTTP Caching and PHP
David de Boer
 
PDF
Resource Registries: Plone Conference 2014
Rob Gietema
 
PDF
Talk about html5 security
Huang Toby
 
PDF
Resource registries plone conf 2014
Ramon Navarro
 
PDF
OWASP Top 10 at International PHP Conference 2014 in Berlin
Tobias Zander
 
PDF
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQ
Michelangelo van Dam
 
PDF
ACL in CodeIgniter
mirahman
 
Django cryptography
Erik LaBianca
 
PHP SA 2014 - Releasing Your Open Source Project
xsist10
 
20160905 - BrisJS - nightwatch testing
Vladimir Roudakov
 
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
pondypaiyan
 
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...
D
 
Things Your Mother Didnt Tell You About Bundle Configurations - Symfony Live…
D
 
Hadoop Security Now and Future
tcloudcomputing-tw
 
What mom never told you about bundle configurations - Symfony Live Paris 2012
D
 
Blog Hacks 2011
Yusuke Wada
 
Web security
davidahaskins
 
Advanced symfony Techniques
Kris Wallsmith
 
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
SreejithVP7
 
Rails Security
Wen-Tien Chang
 
HTTP Caching and PHP
David de Boer
 
Resource Registries: Plone Conference 2014
Rob Gietema
 
Talk about html5 security
Huang Toby
 
Resource registries plone conf 2014
Ramon Navarro
 
OWASP Top 10 at International PHP Conference 2014 in Berlin
Tobias Zander
 
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQ
Michelangelo van Dam
 
ACL in CodeIgniter
mirahman
 
Ad

More from Spin Lai (6)

PDF
Django User Management & Social Authentication
Spin Lai
 
PDF
Django class based views for beginners
Spin Lai
 
PDF
Bdd for legacy system
Spin Lai
 
PDF
Speed up your web development
Spin Lai
 
PDF
Hitcon2013 overview
Spin Lai
 
PDF
The django book - Chap10 : Advanced Models
Spin Lai
 
Django User Management & Social Authentication
Spin Lai
 
Django class based views for beginners
Spin Lai
 
Bdd for legacy system
Spin Lai
 
Speed up your web development
Spin Lai
 
Hitcon2013 overview
Spin Lai
 
The django book - Chap10 : Advanced Models
Spin Lai
 

Recently uploaded (20)

PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Human Resources Information System (HRIS)
Amity University, Patna
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 

Two scoops of Django - Security Best Practices

  • 1. Two Scoops of Django Security Best Practices Spin Lai
  • 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