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

Related tags

Django hacktoberfest
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
Money fields for Django forms and models.

django-money A little Django app that uses py-moneyed to add support for Money fields in your models and forms. Django versions supported: 1.11, 2.1,

null 1.4k Jan 6, 2023
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 Jan 7, 2023
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
Displaying objects on maps in the Django views and administration site.

DjangoAdminGeomap library The free, open-source DjangoAdminGeomap library is designed to display objects on the map in the Django views and admin site

Vitaly Bogomolov 31 Dec 28, 2022
Get inside your stronghold and make all your Django views default login_required

Stronghold Get inside your stronghold and make all your Django views default login_required Stronghold is a very small and easy to use django app that

Mike Grouchy 384 Nov 23, 2022
Django's class-based generic views are awesome, let's have more of them.

Django Extra Views - The missing class-based generic views for Django Django-extra-views is a Django package which introduces additional class-based v

Andy Ingram 1.3k Jan 4, 2023
Super simple bar charts for django admin list views visualizing the number of objects based on date_hierarchy using Chart.js.

Super simple bar charts for django admin list views visualizing the number of objects based on date_hierarchy using Chart.js.

foorilla LLC 4 May 18, 2022
A set of high-level abstractions for Django forms

django-formtools Django's "formtools" is a set of high-level abstractions for Django forms. Currently for form previews and multi-step forms. This cod

Jazzband 621 Dec 30, 2022
Django project starter on steroids: quickly create a Django app AND generate source code for data models + REST/GraphQL APIs (the generated code is auto-linted and has 100% test coverage).

Create Django App ?? We're a Django project starter on steroids! One-line command to create a Django app with all the dependencies auto-installed AND

imagine.ai 68 Oct 19, 2022
Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project

Django URL Shortener Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project Install this package to your Dja

Rishav Sinha 4 Nov 18, 2021
A beginner django project and also my first Django project which involves shortening of a longer URL into a short one using a unique id.

Django-URL-Shortener A beginner django project and also my first Django project which involves shortening of a longer URL into a short one using a uni

Rohini Rao 3 Aug 8, 2021
Django-pwned - A collection of django password validators

Django Pwned A collection of django password validators. Compatibility Python: 3

Quera 22 Jun 27, 2022
Utilities to make function-based views cleaner, more efficient, and better tasting.

django-fbv Utilities to make Django function-based views cleaner, more efficient, and better tasting. ?? ?? Complete documentation: https://django-fbv

Adam Hill 49 Dec 30, 2022
☄️ Google Forms autofill script

lazrr 'Destroy Them With Lazers' - Knife Party, 2011 Google Forms autofill script Installation: pip3 install -r requirements.txt Usage: python3 lazrr.

Serezha Rakhmanov 12 Jun 4, 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
Dockerizing Django with Postgres, Gunicorn, Nginx and Certbot. A fully Django starter project.

Dockerizing Django with Postgres, Gunicorn, Nginx and Certbot ?? Features A Django stater project with fully basic requirements for a production-ready

null 8 Jun 27, 2022
Notes-Django: an advanced project to save notes in Django. where users are able to Create, Read, Update and Delete their notes.

An advanced software to keep you notes. It allows users to perform CRUD operations on theirs Notes. Was implemented Authorization and Authentication

Edilson Pateguana 1 Feb 5, 2022
This a Django TODO app project and practiced how to deploy and publish the project to Heroku

ToDo App Demo | Project Table of Contents Overview Built With Features How to use Acknowledgements Contact Overview Built With HTML CSS JS Django How

Cetin OGUT 1 Nov 19, 2021
pytest-django allows you to test your Django project/applications with the pytest testing tool.

pytest-django allows you to test your Django project/applications with the pytest testing tool.

pytest-dev 1.1k Dec 14, 2022