A collection of models, views, middlewares, and forms to help secure a Django project.

Related tags

Djangohacktoberfest
Overview

Django-Security

Build Status

This package offers a number of models, views, middlewares and forms to facilitate security hardening of Django applications.

Full documentation

Automatically generated documentation of django-security is available on Read The Docs:

Requirements

  • Python >= 3.6
  • Django >= 1.11

For Django < 1.8 use django-security==0.9.4. For Django < 1.11 use django-security==0.11.3.

Note: For versions prior to 0.10.0, datetime objects were being added to the session and required Django's PickleSerializer for (de)serializing. This has now been changed so that the strings of these datetimes are being stored instead. If you are still using PickleSerializer for this reason, we suggest switching to Django's default JSONSerializer (default since Django 1.6) for better security.

Installation

Install from Python packages repository:

pip install django-security

If you prefer the latest development version, install from django-security repository on GitHub:

git clone https://github.com/sdelements/django-security.git
cd django-security
sudo python setup.py install

Adding to Django application's settings.py file:

INSTALLED_APPS = (
    ...
    'security',
    ...
)

Pre-Django 1.10, middleware modules can be added to MIDDLEWARE_CLASSES list in settings file:

MIDDLEWARE_CLASSES = (
    ...
    'security.middleware.DoNotTrackMiddleware',
    'security.middleware.ContentNoSniff',
    'security.middleware.XssProtectMiddleware',
    'security.middleware.XFrameOptionsMiddleware',
)

After Django 1.10, middleware modules can be added to MIDDLEWARE list in settings file:

MIDDLEWARE = (
    ...
    'security.middleware.DoNotTrackMiddleware',
    'security.middleware.ContentNoSniff',
    'security.middleware.XssProtectMiddleware',
    'security.middleware.XFrameOptionsMiddleware',
)

Unlike the modules listed above, some other modules require configuration settings, fully described in django-security documentation. Brief description is provided below.

Middleware

Provided middleware modules will modify web application's output and input and in most cases requires no or minimum configuration.

Middleware Description Configuration
ClearSiteDataMiddleware Send Clear-Site-Data header in HTTP response for any page that has been whitelisted. Recommended. Required.
ContentNoSniff DEPRECATED: Will be removed in future releases, consider django.middleware.security.SecurityMiddleware via SECURE_CONTENT_TYPE_NOSNIFF setting.
Disable possibly insecure autodetection of MIME types in browsers. Recommended.
None.
ContentSecurityPolicyMiddleware Send Content Security Policy (CSP) header in HTTP response. Recommended, requires careful tuning. Required.
DoNotTrackMiddleware Read user browser's DoNotTrack preference and pass it to application. Recommended, requires implementation in views and templates. None.
LoginRequiredMiddleware Requires a user to be authenticated to view any page on the site that hasn't been white listed. Required.
MandatoryPasswordChangeMiddleware Redirects any request from an authenticated user to the password change form if that user's password has expired. Required.
NoConfidentialCachingMiddleware Adds No-Cache and No-Store headers to confidential pages. Required.
P3PPolicyMiddleware DEPRECATED: Will be removed in future releases.
Adds the HTTP header attribute specifying compact P3P policy.
Required.
ReferrerPolicyMiddleware Specify when the browser will set a `Referer` header. Optional.
SessionExpiryPolicyMiddleware Expire sessions on browser close, and on expiry times stored in the cookie itself. Required.
StrictTransportSecurityMiddleware DEPRECATED: Will be removed in future releases, consider django.middleware.security.SecurityMiddleware via SECURE_HSTS_SECONDS, SECURE_HSTS_INCLUDE_SUBDOMAINS and SECURE_HSTS_PRELOAD settings.
Enforce SSL/TLS connection and disable plaintext fall-back. Recommended for SSL/TLS sites.
Optional.
XFrameOptionsMiddleware Disable framing of the website, mitigating Clickjacking attacks. Recommended. Optional.
XssProtectMiddleware DEPRECATED: Will be removed in future releases, consider django.middleware.security.SecurityMiddleware via SECURE_BROWSER_XSS_FILTER setting.
Enforce browser's Cross Site Scripting protection. Recommended.
None.

Views

csp_report

View that allows reception of Content Security Policy violation reports sent by browsers in response to CSP header set by ``ContentSecurityPolicyMiddleware`. This should be used only if long term, continuous CSP report analysis is required. For one time CSP setup CspBuilder is much simpler.

This view can be configured to either log received reports or store them in database. See documentation for details.

require_ajax

A view decorator which ensures that the request being processed by view is an AJAX request. Example usage:

@require_ajax
def myview(request):
    ...

Models

CspReport

Content Security Policy violation report object. Only makes sense if ContentSecurityPolicyMiddleware and csp_report view are used. With this model, the reports can be then analysed in Django admin site.

PasswordExpiry

Associate a password expiry date with a user.

Logging

All django-security modules send important log messages to security facility. The application should configure a handler to receive them:

LOGGING = {
    ...
    'loggers': {
        'security': {
            'handlers': ['console',],
            'level': 'INFO',
            'propagate': False,
            'formatter': 'verbose',
        },
    },
    ...
}
Comments
  • Django 2 Compatible Changes

    Django 2 Compatible Changes

    Made the necessary changes to ensure the code is Django 2 compatible:

    • Made some changes to ensure the code works with Django 1.11 and Django 2.2, as well as updating the test cases to run against both Django 1.11 and Django 2.2
    • Updated the README, requirements and other parts of the code to make sure we reference Django 1.11 and higher.
    • Made changes to the test cases to ensure we only load the required middleware to test functionality. This should help reduce interference from other middleware.
    • Minor code clean up

    Refs: PAS-197

    opened by tvle236 12
  • Add ClearSiteDataMiddleware

    Add ClearSiteDataMiddleware

    Add a ClearSiteDataMiddleware and respective django settings.

    CLEAR_SITE_DATA_URL_WHITELIST - whitelist of URLs that Clear-Site-Data response header is applied to (eg. /accounts/logout/) CLEAR_SITE_DATA_DIRECTIVES - what directives to apply (defaults to wildcard)

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data

    opened by Gee19 6
  • Changed explicit User relation to configurable setting

    Changed explicit User relation to configurable setting

    because hardcoding User in a ForeignKey stops people from specifing alternative user models using settings.AUTH_USER_MODEL

    This fix silences fields.E301 error raised by Django system check (https://docs.djangoproject.com/en/1.8/ref/checks/#related-fields) for users that, for example, use django-authtools or declare own user models based on django.contrib.auth.models.AbstractUser.

    Thanks and best regards :), Marek

    opened by niktto 6
  • PEP8 formatting and style improvements

    PEP8 formatting and style improvements

    This change includes the following:

    • PEP8 compliance
    • Compliance with a number of recommendations given by the OpenStack style guide and PEP8 Naming
    • Style testing with Tox
    • Minor documentation formatting fixes
    • Refactoring of ContentSecurityPolicyMiddleware._csp_builder to reduce McCabe complexity to below 10.
    • Travis config so that auto-testing of pull requests can be set up.

    The code style has changed quite significantly. The main motivation behind this is that PEP8 is considered to be a good standard that code should strive to adhere to, however in addition to this, I've reformatted the code to provide clearer diffs in future pull requests.

    opened by danpalmer 6
  • Add X_FRAME_OPTIONS_EXCLUDE_URLS setting

    Add X_FRAME_OPTIONS_EXCLUDE_URLS setting

    This setting provides means to whitelist certain pages that are expected to be hosted in an <iframe> while still protecting the rest of the site.

    opened by cassiemeharry 6
  • Configurable Password Expiration rules for newly created users.

    Configurable Password Expiration rules for newly created users.

    I'd like to migrate to django-security, unfortunately this means two things need to happen (in my codebase/environment, or in the larger project...somewhere)

    Currently, with the password expiry middleware enabled, we'll create new PasswordExpiry objects for each user when my tests are run. because auto_now_add=True on PasswordExpiry.password_expiry_date this means that many of my view-based integration tests are failing because all users that get created via models also get their password expired.

    If instead of auto_now_add=True there were a default that checked a setting, this could be configurable per installation.

    This would save me from re-writing several hundred tests in order to implement this feature, and it would ease the transition into production for my current project.

    opened by issackelly 5
  • Add Support for Django 1.10

    Add Support for Django 1.10

    Hi There,

    I have made a quick hack to your code to add support for Django 1.10 as suggested here:

    https://docs.djangoproject.com/en/1.10/topics/http/middleware/#upgrading-pre-django-1-10-style-middleware

    Thanks

    opened by antonisppn 4
  • CSP report changes

    CSP report changes

    These changes improve handling of CSP reports as tested with real-life browsers. The CspReport model now also records user agent and reporting IP for easier debugging.

    opened by kravietz 4
  • Add support for new Content-Type

    Add support for new Content-Type

    New Content-Type should be "application/csp-report" https://w3c.github.io/webappsec-csp/

    This should be merged (or fixed otherwise) ASAP because current content_type check breaks CSP reporting from new browsers.

    opened by jozo 3
  • Remove bytes from migrations

    Remove bytes from migrations

    In the latest Django 1.8 + it is not necessary to pass strings as byte arrays in migrations.

    This appears to be a legacy code. And because of this, Django's checks for migrations identifies that migrations need to be created, where in fact nothing has changed.

    opened by rahulkatragadda 3
  • For Django 2.0+  'on_delete' missing

    For Django 2.0+ 'on_delete' missing

    I'm using Django 2.0.2. Since Django 2.x, on_delete is a required argument: https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.ForeignKey.on_delete

    I'm getting the following stack trace when I attempt to instal django-security:

        Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10520c7b8>
    Traceback (most recent call last):
      File "/Users/nina/Documents/Sites/project-name/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
        fn(*args, **kwargs)
      File "/Users/nina/Documents/Sites/project-name/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run
        autoreload.raise_last_exception()
      File "/Users/nina/Documents/Sites/project-name/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception
        raise _exception[1]
      File "/Users/nina/Documents/Sites/project-name/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute
        autoreload.check_errors(django.setup)()
      File "/Users/nina/Documents/Sites/project-name/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
        fn(*args, **kwargs)
      File "/Users/nina/Documents/Sites/project-name/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
        apps.populate(settings.INSTALLED_APPS)
      File "/Users/nina/Documents/Sites/project-name/venv/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate
        app_config.import_models()
      File "/Users/nina/Documents/Sites/project-name/venv/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models
        self.models_module = import_module(models_module_name)
      File "/Users/nina/Documents/Sites/project-name/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 994, in _gcd_import
      File "<frozen importlib._bootstrap>", line 971, in _find_and_load
      File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
      File "<frozen importlib._bootstrap_external>", line 678, in exec_module
      File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
      File "/Users/nina/Documents/Sites/project-name/venv/lib/python3.6/site-packages/security/models.py", line 14, in <module>
        class PasswordExpiry(models.Model):
      File "/Users/nina/Documents/Sites/project-name/venv/lib/python3.6/site-packages/security/models.py", line 27, in PasswordExpiry
        user = models.ForeignKey(USER_MODEL, unique=True)
    TypeError: __init__() missing 1 required positional argument: 'on_delete'
    
    opened by ninapavlich 3
  • Support named URL patterns for LOGIN_URL

    Support named URL patterns for LOGIN_URL

    Closes #87

    I've added a test which fails on master and succeeds with this PR.

    (I also loosened some of the flake8 restrictions to get existing code to pass. I'd be happy to remove those restrictions and update the code if you prefer)

    opened by vkurup 0
  • LoginRequiredMiddleware breaks LOGIN_URL is a named URL

    LoginRequiredMiddleware breaks LOGIN_URL is a named URL

    opened by vkurup 0
  • Support for nonce-<base64-value>

    Support for nonce-

    Hi, I've created a subclass of ContentSecurityPolicyMiddleware and an accompanying template context processor so I can do:

    <script type="text/javascript" nonce="{{ csp_nonce }}">
    </script>
    

    Is there any interest in this? If so I can make a PR.

    Thanks!

    opened by daniel5gh 1
  • SessionSecurityMiddleware Client Activity Keep-Alive

    SessionSecurityMiddleware Client Activity Keep-Alive

    I really like the all-in-one convenience of django-security, but the SessionSecurityMiddleware implementation lacks the client-side keep-alive available in django-session-security. The keep-alive is important to us because our product is used to guide a conversation with a customer so our users are often "active" on a page without server-side interaction.

    Any interest adding a keep-alive feature to django-security? If so, what approach would you prefer? The licenses look compatible so it seems like any of the following would work:

    • Replace SessionSecurityMiddleware with the django-session-security implementation
    • Port the JS code to SessionSecurityMiddleware
    • Include both in django-security
    opened by claytondaley 3
Releases(0.14.0)
Owner
SD Elements
SD Elements is a software security requirements management solution, built by Security Compass.
SD Elements
Drf-stripe-subscription - An out-of-box Django REST framework solution for payment and subscription management using Stripe

Drf-stripe-subscription - An out-of-box Django REST framework solution for payment and subscription management using Stripe

Oscar Y Chen 68 Jan 07, 2023
Strict separation of config from code.

Python Decouple: Strict separation of settings from code Decouple helps you to organize your settings so that you can change parameters without having

Henrique Bastos 2.3k Jan 04, 2023
Service request portal on top of Ansible Tower

Squest - A service request portal based on Ansible Tower Squest is a Web portal that allow to expose Tower based automation as a service. If you want

Hewlett Packard Enterprise 183 Jan 04, 2023
A UUIDField for Django

django-uuidfield Provides a UUIDField for your Django models. Installation Install it with pip (or easy_install): pip install django-uuidfield Usage

David Cramer 265 Nov 30, 2022
Hotwired/Turbo Django response helpers

This package provides helpers for server-side rendering of Hotwired/Turbo streams and frames. Disclaimer: the Hotwired/Turbo client libraries are, at

Hotwire for Django 66 Apr 07, 2022
Loguru is an exceeding easy way to do logging in Python

Django Easy Logging Easy Django logging with Loguru Loguru is an exceeding easy way to do logging in Python. django-easy-logging makes it exceedingly

Neutron Sync 8 Oct 17, 2022
Django Federated Login provides an authentication bridge between Django projects and OpenID-enabled identity providers.

Django Federated Login Django Federated Login provides an authentication bridge between Django projects and OpenID-enabled identity providers. The bri

Bouke Haarsma 18 Dec 29, 2020
Generate generic activity streams from the actions on your site. Users can follow any actors' activities for personalized streams.

Django Activity Stream What is Django Activity Stream? Django Activity Stream is a way of creating activities generated by the actions on your site. I

Justin Quick 2.1k Dec 29, 2022
Neighbourhood - A python-django web app to help the residence of a given neighborhood know their surrounding better

Neighbourhood A python-django web app to help the residence of a given neighborh

Levy Omolo 4 Aug 25, 2022
DRF_commands is a Django package that helps you to create django rest framework endpoints faster using manage.py.

DRF_commands is a Django package that helps you to create django rest framework endpoints faster using manage.py.

Mokrani Yacine 2 Sep 28, 2022
A CBV to handle multiple forms in one view

django-shapeshifter A common problem in Django is how to have a view, especially a class-based view that can display and process multiple forms at onc

Kenneth Love 167 Nov 26, 2022
A Django application that provides country choices for use with forms, flag icons static files, and a country field for models.

Django Countries A Django application that provides country choices for use with forms, flag icons static files, and a country field for models. Insta

Chris Beaven 1.2k Dec 31, 2022
A package to handle images in django

Django Image Tools Django Image Tools is a small app that will allow you to manage your project's images without worrying much about image sizes, how

The Bonsai Studio 42 Jun 02, 2022
Django React - Purity Dashboard (Open-Source) | AppSeed

Django React Purity Dashboard Start your Development with an Innovative Admin Template for Chakra UI and React. Purity UI Dashboard is built with over

App Generator 19 Sep 19, 2022
A Django based shop system

django-SHOP Django-SHOP aims to be a the easy, fun and fast e-commerce counterpart to django-CMS. Here you can find the full documentation for django-

Awesto 2.9k Dec 30, 2022
Customize the behavior of django.contrib.auth permissions.

Customizando o comportamento do django.contrib.auth. O que queremos? Não criar as permissões padrões automaticamente (add, delete, view, read). Criar

Henrique Bastos 7 Nov 26, 2022
A Django Webapp performing CRUD operations on Library Database.

CRUD operations - Django Library Database A Django Webapp performing CRUD operations on Library Database. Tools & Technologies used: Django MongoDB HT

1 Dec 05, 2021
Declarative model lifecycle hooks, an alternative to Signals.

Django Lifecycle Hooks This project provides a @hook decorator as well as a base model and mixin to add lifecycle hooks to your Django models. Django'

Robert Singer 1k Dec 31, 2022
Bringing together django, django rest framework, and htmx

This is Just an Idea There is no code, this README just represents an idea for a minimal library that, as of now, does not exist. django-htmx-rest A l

Jack DeVries 5 Nov 24, 2022
Django Rest Framework + React application.

Django Rest Framework + React application.

2 Dec 19, 2022