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
Djang Referral System

Djang Referral System About | Features | Technologies | Requirements | Starting | License | Author 🎯 About I created django referral system and I wan

Alex Kotov 5 Oct 25, 2022
django app that allows capture application metrics by each user individually

Django User Metrics django app that allows capture application metrics by each user individually, so after you can generate reports with aggregation o

Reiner Marquez 42 Apr 28, 2022
Show how the redis works with Python (Django).

Redis Leaderboard Python (Django) Show how the redis works with Python (Django). Try it out deploying on Heroku (See notes: How to run on Google Cloud

Tom Xu 4 Nov 16, 2021
A app for managing lessons with Django

Course Notes A app for managing lessons with Django Some Ideas

Motahhar.Mokfi 6 Jan 28, 2022
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
An URL Shortener with Basic Features.

Simple Url Shortener What is that? Yet another url shortener built with Django framework. Preview HOW TO RUN? 1. Virtual Environment First create a vi

Ethem Turgut 6 Jan 25, 2022
This is a repository for collecting global custom management extensions for the Django Framework.

Django Extensions Django Extensions is a collection of custom extensions for the Django Framework. Getting Started The easiest way to figure out what

Django Extensions 6k Dec 26, 2022
A Django app to accept payments from various payment processors via Pluggable backends.

Django-Merchant Django-Merchant is a django application that enables you to use multiple payment processors from a single API. Gateways Following gate

Agiliq 997 Dec 24, 2022
This repository contains django library management system project.

Library Management System Django ** INSTALLATION** First of all install python on your system. Then run pip install -r requirements.txt to required se

whoisdinanath 1 Dec 26, 2022
Repo for All the Assignments I have to submit for Internship Application !😅

Challenges Repository for All the Assignments I have to submit for Internship Application ! 😅 As You know, When ever We apply for an Internship, They

keshav Sharma 1 Sep 08, 2022
Tutorial para o projeto negros.dev - A Essência do Django

Negros Dev Tutorial para o site negros.dev Este projeto foi feito com: Python 3.8.9 Django 3.1.8 Bootstrap 4.0 Como rodar o projeto? Clone esse reposi

Regis Santos 6 Aug 12, 2022
Application made in Django to generate random passwords as based on certain criteria .

PASSWORD GENERATOR Welcome to Password Generator About The App Password Generator is an Open Source project brought to you by Iot Lab,KIIT and it brin

IoT Lab KIIT 3 Oct 21, 2021
An insecure login and registration website with Django.

An insecure login and registration website with Django.

Luis Quiñones Requelme 1 Dec 05, 2021
Yet another Django audit log app, hopefully the simplest one.

django-easy-audit Yet another Django audit log app, hopefully the easiest one. This app allows you to keep track of every action taken by your users.

Natán 510 Jan 02, 2023
A handy tool for generating Django-based backend projects without coding. On the other hand, it is a code generator of the Django framework.

Django Sage Painless The django-sage-painless is a valuable package based on Django Web Framework & Django Rest Framework for high-level and rapid web

sageteam 51 Sep 15, 2022
Alt1-compatible widget host for RuneScape 3

RuneKit Alt1-compatible toolbox for RuneScape 3, for Linux and macOS. Compatibility macOS installation guide Running This project use Poetry as packag

Manatsawin Hanmongkolchai 75 Nov 28, 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
Inject an ID into every log message from a Django request. ASGI compatible, integrates with Sentry, and works with Celery

Django GUID Now with ASGI support! Django GUID attaches a unique correlation ID/request ID to all your log outputs for every request. In other words,

snok 300 Dec 29, 2022
Simple Login Logout System using Django, JavaScript and ajax.

Djanog-UserAuthenticationSystem Technology Use #version Python 3.9.5 Django 3.2.7 JavaScript --- Ajax Validation --- Login and Logout Functionality, A

Bhaskar Mahor 3 Mar 26, 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