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
Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly.

Cookiecutter Django Powered by Cookiecutter, Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly. Documentati

10.1k Jan 08, 2023
A small and lightweight imageboard written with Django

Yuu A small and lightweight imageboard written with Django. What are the requirements? Python 3.7.x PostgreSQL 14.x Redis 5.x FFmpeg 4.x Why? I don't

mint.lgbt 1 Oct 30, 2021
A simple Django dev environment setup with docker for demo purposes for GalsenDev community

GalsenDEV Docker Demo This is a basic Django dev environment setup with docker and docker-compose for a GalsenDev Meetup. The main purposes was to mak

3 Jul 03, 2021
Django channels basic chat

Django channels basic chat

Dennis Ivy 41 Dec 24, 2022
Bleach is an allowed-list-based HTML sanitizing library that escapes or strips markup and attributes

Bleach Bleach is an allowed-list-based HTML sanitizing library that escapes or strips markup and attributes. Bleach can also linkify text safely, appl

Mozilla 2.5k Dec 29, 2022
A fresh approach to autocomplete implementations, specially for Django. Status: v3 stable, 2.x.x stable, 1.x.x deprecated. Please DO regularely ping us with your link at #yourlabs IRC channel

Features Python 2.7, 3.4, Django 2.0+ support (Django 1.11 (LTS), is supported until django-autocomplete-light-3.2.10), Django (multiple) choice suppo

YourLabs 1.7k Jan 01, 2023
A GitHub Action for checking Django migrations

🔍 Django migrations checker A GitHub Action for checking Django migrations About This repository contains a Github Action that checks Django migratio

Oda 5 Nov 15, 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 simple porfolio with Django, Bootstrap and Sqlite3

Django Portofolio Example this is a basic portfolio in dark mode Installation git clone https://github.com/FaztWeb/django-portfolio-simple.git cd djan

Fazt Web 16 Sep 26, 2022
A starter template for building a backend with Django and django-rest-framework using docker with PostgreSQL as the primary DB.

Django-Rest-Template! This is a basic starter template for a backend project with Django as the server and PostgreSQL as the database. About the templ

Akshat Sharma 11 Dec 06, 2022
Redia Cache implementation in django.

django-redis Recipe APP Simple Recipe app which shows different kinds off recipe to the user. Why Cache ? Accessing data from cache is much faster tha

Avinash Alanjkar 1 Sep 21, 2022
File and Image Management Application for django

Django Filer django Filer is a file management application for django that makes handling of files and images a breeze. Contributing This is a an open

django CMS Association 1.6k Dec 28, 2022
Exploit Discord's cache system to remote upload payloads on Discord users machines

Exploit Discord's cache system to hide payloads PoC Remote upload embedded payload from image using EOF to Discord users machines through cache. Depen

cs 169 Dec 20, 2022
A music recommendation REST API which makes a machine learning algorithm work with the Django REST Framework

music-recommender-rest-api A music recommendation REST API which makes a machine learning algorithm work with the Django REST Framework How it works T

The Reaper 1 Sep 28, 2021
WeatherApp - Simple Python Weather App

Weather App Please star this repo if you like ⭐ It's motivates me a lot! Stack A

Ruslan Shvetsov 3 Apr 18, 2022
An extremely fast JavaScript and CSS bundler and minifier

Website | Getting started | Documentation | Plugins | FAQ Why? Our current build tools for the web are 10-100x slower than they could be: The main goa

Evan Wallace 34.2k Jan 04, 2023
System checks for your project's environment.

django-version-checks System checks for your project's environment. Requirements Python 3.6 to 3.9 supported. Django 2.2 to 3.2 supported. Are your te

Adam Johnson 33 Dec 22, 2022
A pickled object field for Django

django-picklefield About django-picklefield provides an implementation of a pickled object field. Such fields can contain any picklable objects. The i

Gintautas Miliauskas 167 Oct 18, 2022
Djangoblog - A blogging platform built on Django and Python.

djangoblog 👨‍💻 A blogging platform built on Django and Python

Lewis Gentle 1 Jan 10, 2022
Analytics services for Django projects

django-analytical The django-analytical application integrates analytics services into a Django project. Using an analytics service with a Django proj

Jazzband 1.1k Dec 31, 2022