two scoops of django - security best practices

78
Two Scoops of Django Security Best Practices Spin Lai

Upload: spin-lai

Post on 16-Apr-2017

4.188 views

Category:

Software


2 download

TRANSCRIPT

Page 1: Two scoops of Django - Security Best Practices

Two Scoops of DjangoSecurity Best Practices

Spin Lai

Page 2: Two scoops of Django - Security Best Practices
Page 3: Two scoops of Django - Security Best Practices

I. Django Configurations

II. Django Security Features

III. Django Admin

IV. What Else ?

Page 4: Two scoops of Django - Security Best Practices

I. Django Configurations

II. Django Security Features

III. Django Admin

IV. What Else ?

Page 5: Two scoops of Django - Security Best Practices

Django Configurations

Designate Settings DEBUG / TEMPLATE_DEBUG ALLOWED_HOSTS SECRET_KEY

!

Page 6: Two scoops of Django - Security Best Practices

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]

Page 7: Two scoops of Django - Security Best Practices

Django Configurations

Designate Settings DEBUG / TEMPLATE_DEBUG ALLOWED_HOSTS SECRET_KEY

!

DEBUG = False !TEMPLATE_DEBUG = False

Page 8: Two scoops of Django - Security Best Practices

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 ! ]

Page 9: Two scoops of Django - Security Best Practices

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.

Page 10: Two scoops of Django - Security Best Practices

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)

Page 11: Two scoops of Django - Security Best Practices

I. Django Configurations

II. Django Security Features

III. Django Admin

IV. What Else ?

Page 12: Two scoops of Django - Security Best Practices

Django Security Features

XSS Protection CSRF Protection Injection Protection Clickjacking Protection SSL / HTTPS Password Storage Data Validation

Page 13: Two scoops of Django - Security Best Practices

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

Page 14: Two scoops of Django - Security Best Practices

Django Security Features

XSS Protection CSRF Protection Injection Protection Clickjacking Protection SSL / HTTPS Password Storage Data Validation

Page 15: Two scoops of Django - Security Best Practices

CSRF protection

• Django CSRF Protection Workflow

• CSRF Protection for AJAX Request

• HTML Search Form

• CsrfViewMiddleware rather than @csrf_protect

• Be careful with @csrf_exempt

Page 16: Two scoops of Django - Security Best Practices

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

Page 17: Two scoops of Django - Security Best Practices

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

Page 18: Two scoops of Django - Security Best Practices

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); };

Page 19: Two scoops of Django - Security Best Practices

CSRF protection

• Django CSRF Protection Workflow

• CSRF Protection for AJAX Request

• HTML Search Form

• CsrfViewMiddleware rather than @csrf_protect

• Be careful with @csrf_exempt

Page 20: Two scoops of Django - Security Best Practices

CSRF protection

• Django CSRF Protection Workflow

• CSRF Protection for AJAX Request

• HTML Search Form

• CsrfViewMiddleware rather than @csrf_protect

• Be careful with @csrf_exempt

Page 21: Two scoops of Django - Security Best Practices

CSRF protection

• Django CSRF Protection Workflow

• CSRF Protection for AJAX Request

• HTML Search Form

• CsrfViewMiddleware rather than @csrf_protect

• Be careful with @csrf_exempt

Page 22: Two scoops of Django - Security Best Practices

Django Security Features

XSS Protection CSRF Protection Injection Protection Clickjacking Protection SSL / HTTPS Password Storage Data Validation

Page 23: Two scoops of Django - Security Best Practices

Injection protection

• Script Injection

• SQL Injection

Page 24: Two scoops of Django - Security Best Practices

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

Page 25: Two scoops of Django - Security Best Practices

Injection protection

• Script Injection

• SQL Injection

‣ Django Queryset escape varaibles automatically ‣ Be careful to escape raw SQL properly ‣ Exercise caution when using extra()

Page 26: Two scoops of Django - Security Best Practices

Django Security Features

XSS Protection CSRF Protection Injection Protection Clickjacking Protection SSL / HTTPS Password Storage Data Validation

Page 27: Two scoops of Django - Security Best Practices

Clickjacking protection

• `X-Frame-Options` HTTP header

• Configurations

• @xframe_options_exempt

• Browsers Support

Page 28: Two scoops of Django - Security Best Practices

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

Page 29: Two scoops of Django - Security Best Practices

Clickjacking protection

• `X-Frame-Options` HTTP header

• Configurations

• @xframe_options_exempt

• Browsers SupportMIDDLEWARE_CLASSES = ( ... 'django.middleware.clickjacking.XFrameOptionsMiddleware', ... )

Page 30: Two scoops of Django - Security Best Practices

Clickjacking protection

• `X-Frame-Options` HTTP header

• Configurations

• @xframe_options_exempt

• Browsers Support# Default X_FRAME_OPTIONS = 'SAMEORIGIN' !X_FRAME_OPTIONS = 'DENY'

Page 31: Two scoops of Django - Security Best Practices

Clickjacking protection

• `X-Frame-Options` HTTP header

• Configurations

• @xframe_options_exempt

• Browsers Support

Page 32: Two scoops of Django - Security Best Practices

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+

Page 33: Two scoops of Django - Security Best Practices

Django Security Features

XSS Protection CSRF Protection Injection Protection Clickjacking Protection SSL / HTTPS Password Storage Data Validation

Page 34: Two scoops of Django - Security Best Practices

SSL / HTTPS

• HTTPS Everywhere !

• Secure Cookies

• HSTS

• Packages

Page 35: Two scoops of Django - Security Best Practices

SSL / HTTPS

• HTTPS Everywhere !

• Secure Cookies

• HSTS

• Packages

‣ Web server configuration ‣ Django middleware ‣ SSL certificate from reputable source

Page 36: Two scoops of Django - Security Best Practices

SSL / HTTPS

• HTTPS Everywhere !

• Secure Cookies

• HSTS

• Packages

SECURE_PROXY_SSL_HEADER = False !$ export HTTPS=on

Page 37: Two scoops of Django - Security Best Practices

SSL / HTTPS

• HTTPS Everywhere !

• Secure Cookies

• HSTS

• PackagesSESSION_COOKIE_SECURE = True !CSRF_COOKIE_SECURE = True

Page 38: Two scoops of Django - Security Best Practices

SSL / HTTPS

• HTTPS Everywhere !

• Secure Cookies

• HSTS

• Packages

‣Redirect HTTP links to HTTPS ‣Web server level configuration ‣HSTS-compliant browsers

Page 39: Two scoops of Django - Security Best Practices

SSL / HTTPS

• HTTPS Everywhere !

• Secure Cookies

• HSTS

• Packages

Strict-Transport-Security: max-age=31536000, includeSubDomains

Page 40: Two scoops of Django - Security Best Practices

SSL / HTTPS

• HTTPS Everywhere !

• Secure Cookies

• HSTS

• Packages ‣ django-sslify ‣ django-secure ‣ django-hstsmiddleware

Page 41: Two scoops of Django - Security Best Practices

Django Security Features

XSS Protection CSRF Protection Injection Protection Clickjacking Protection SSL / HTTPS Password Storage Data Validation

Page 42: Two scoops of Django - Security Best Practices

Password Storage

• PBKDF2 + SHA256

• User.password

• PASSWORD_HASHER

• Use bcrypt

• Increase work factor

Page 43: Two scoops of Django - Security Best Practices

Password Storage

• PBKDF2 + SHA256

• User.password

• PASSWORD_HASHER

• Use bcrypt

• Increase work factor

Page 44: Two scoops of Django - Security Best Practices

Password Storage

• PBKDF2 + SHA256

• User.password

• PASSWORD_HASHER

• Use bcrypt

• Increase work factor

<algorithm>$<iteration>$<salt>$<hash>

Page 45: Two scoops of Django - Security Best Practices

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', )

Page 46: Two scoops of Django - Security Best Practices

Password Storage

• PBKDF2 + SHA256

• User.password

• PASSWORD_HASHER

• bcrypt

• Increase work factor

Page 47: Two scoops of Django - Security Best Practices

Password Storage

• PBKDF2 + SHA256

• User.password

• PASSWORD_HASHER

• Use bcrypt

• Increase work factor

Page 48: Two scoops of Django - Security Best Practices

Django Security Features

XSS Protection CSRF Protection Injection Protection Clickjacking Protection SSL / HTTPS Password Storage Data Validation

Page 49: Two scoops of Django - Security Best Practices

Data Validation

• Django Forms

• User-Uploaded Content

Page 50: Two scoops of Django - Security Best Practices

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

Page 51: Two scoops of Django - Security Best Practices

Data Validation

• Django Forms

• User-Uploaded Contentfrom django import forms from .models import Store !class StoreForm(forms.ModelForm): ! class Meta: model = Store # Don't Do this!! excludes = ("pk", "slug", "modified")

Page 52: Two scoops of Django - Security Best Practices

Data Validation

• Django Forms

• User-Uploaded Contentfrom django import forms from .models import Store !class StoreForm(forms.ModelForm): ! class Meta: model = Store # Explicitly specifying what we want fields = ("title", "address", "email")

Page 53: Two scoops of Django - Security Best Practices

Data Validation

• Django Forms

• User-Uploaded Content

‣ Limit upload in web server ‣ FileField / ImageField ‣ python-magic ‣ Validate with specific file type library

Page 54: Two scoops of Django - Security Best Practices

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])

Page 55: Two scoops of Django - Security Best Practices

I. Django Configurations

II. Django Security Features

III. Django Admin

IV. What Else ?

Page 56: Two scoops of Django - Security Best Practices

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

Page 57: Two scoops of Django - Security Best Practices

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

Page 58: Two scoops of Django - Security Best Practices

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

Page 59: Two scoops of Django - Security Best Practices

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

Page 60: Two scoops of Django - Security Best Practices

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

Page 61: Two scoops of Django - Security Best Practices

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

Page 62: Two scoops of Django - Security Best Practices

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

Page 63: Two scoops of Django - Security Best Practices

I. Django Configurations

II. Django Security Features

III. Django Admin

IV. What Else ?

Page 64: Two scoops of Django - Security Best Practices

What else ?

Harden your servers NEVER store credit card data Server monitoring Vulnerability reporting page Keep things up-to-date

Page 65: Two scoops of Django - Security Best Practices

What else ?

Harden your servers NEVER store credit card data Server monitoring Vulnerability reporting page Keep things up-to-date

Page 66: Two scoops of Django - Security Best Practices

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

Page 67: Two scoops of Django - Security Best Practices

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

Page 68: Two scoops of Django - Security Best Practices

What else ?

Harden your servers NEVER store credit card data Server monitoring Vulnerability reporting page Keep things up-to-date

Page 69: Two scoops of Django - Security Best Practices

What else ?

Harden your servers NEVER store credit card data Server monitoring Vulnerability reporting page Keep things up-to-date

Page 70: Two scoops of Django - Security Best Practices

What else ?

Harden your servers NEVER store credit card data Server monitoring Vulnerability reporting page Keep things up-to-date

Page 71: Two scoops of Django - Security Best Practices

What else ?

Harden your servers NEVER store credit card data Server monitoring Vulnerability reporting page Keep things up-to-date

Page 72: Two scoops of Django - Security Best Practices

What else ?

Harden your servers NEVER store credit card data Server monitoring Vulnerability reporting page Keep things up-to-date

Page 73: Two scoops of Django - Security Best Practices

Keep Things Up-to-Date

• Dependencies

• Security Practices

Page 74: Two scoops of Django - Security Best Practices

Keep Things Up-to-Date

• Dependencies

• Security Practiceshttps://www.djangoproject.com/weblog/

Page 75: Two scoops of Django - Security Best Practices

Keep Things Up-to-Date

• Dependencies

• Security Practices

Page 76: Two scoops of Django - Security Best Practices

Keep Things Up-to-Date

• Dependencies

• Security Practices

Page 77: Two scoops of Django - Security Best Practices

Keep Things Up-to-Date

• Dependencies

• Security Practices

Page 78: Two scoops of Django - Security Best Practices

Thank You