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
A Django web application that shortens long URLs. This is a demo project to show off my tech abilities.

Django URL Shortener This project is just a complete and production-ready URL shortener web application to show off my tech and coding abilities. Impo

Seyyed Ali Ayati 5 Jan 26, 2022
Django + AWS Elastic Transcoder

Django Elastic Transcoder django-elastic-transcoder is an Django app, let you integrate AWS Elastic Transcoder in Django easily. What is provided in t

StreetVoice 66 Dec 14, 2022
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
Basic implementation of Razorpay payment gateway 💳 with Django

Razorpay Payment Integration in Django 💥 In this project Razorpay payment gateway 💳 is integrated with Django by breaking down the whole process int

ScaleReal 12 Dec 12, 2022
Simple tagging for django

django-taggit This is a Jazzband project. By contributing you agree to abide by the Contributor Code of Conduct and follow the guidelines. django-tagg

Jazzband 3k Jan 02, 2023
Awesome Django Blog App

Awesome-Django-Blog-App Made with love django as the backend and Bootstrap as the frontend ! i hope that can help !! Project Title Django provides mul

ANAS NABIL 2 Feb 08, 2022
Учебное пособие по основам Django и сопутствующим технологиям

Учебный проект для закрепления основ Django Подробный разбор проекта здесь. Инструкция по запуску проекта на своей машине: Скачиваем репозиторий Устан

Stanislav Garanzha 12 Dec 30, 2022
A Django/Python web app that functions as a digital diary

My Django Diary Full-stack web application that functions as a digital diary using Django, Python, SQLite, HTML & CSS. Things I learned during this pr

1 Sep 30, 2022
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

Daniel Feldroy 10k Dec 31, 2022
Sistema de tratamento e análise de grandes volumes de dados através de técnicas de Data Science

Sistema de tratamento e análise de grandes volumes de dados através de técnicas de data science Todos os scripts, gráficos e relatórios de todas as at

Arthur Quintanilha Neto 1 Sep 05, 2022
🏭 An easy-to-use implementation of Creation Methods for Django, backed by Faker.

Django-fakery An easy-to-use implementation of Creation Methods (aka Object Factory) for Django, backed by Faker. django_fakery will try to guess the

Flavio Curella 93 Oct 12, 2022
Blog focused on skills enhancement and knowledge sharing. Tech Stack's: Vue.js, Django and Django-Ninja

Blog focused on skills enhancement and knowledge sharing. Tech Stack's: Vue.js, Django and Django-Ninja

Wanderson Fontes 2 Sep 21, 2022
Chatbot for ordering and tracking a Pizza.

Pizza Chatbot To start the app, follow the below steps: Clone the repo using the below command: git clone Shreya Shah 1 Jul 15, 2021

A clone of https://virgool.io written in django

Virgool clone A clone of virgool blog written in django Installation first rename the .env.sample to .env and fill it. with docker docker-compose up -

Danial Selmipoor 7 Dec 23, 2022
Buckshot++ is a new algorithm that finds highly stable clusters efficiently.

Buckshot++: An Outlier-Resistant and Scalable Clustering Algorithm. (Inspired by the Buckshot Algorithm.) Here, we introduce a new algorithm, which we

John Jung 1 Jul 02, 2022
A pluggable Django application for integrating PayPal Payments Standard or Payments Pro

Django PayPal Django PayPal is a pluggable application that integrates with PayPal Payments Standard and Payments Pro. See https://django-paypal.readt

Luke Plant 672 Dec 22, 2022
Official clone of the Subversion repository.

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. All documentation is in the "docs" directo

Raymond Penners 3 May 06, 2022
A middleware to log the requests and responses using loguru.

Django Loguru The extension was based on another one and added some extra flavours. One of the biggest problems with the apps is the logging and that

Tiago Silva 9 Oct 11, 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
PEP-484 stubs for django-rest-framework

pep484 stubs for Django REST framework Mypy stubs for DRF 3.12.x. Supports Python 3.6, 3.7, 3.8 and 3.9. Installation pip install djangorestframework-

TypedDjango 303 Dec 27, 2022