django-debreach-2.0.1/0000775000175000017500000000000013547572542017455 5ustar lukepomfreylukepomfrey00000000000000django-debreach-2.0.1/LICENSE0000644000175000017500000000245712644500521020451 0ustar lukepomfreylukepomfrey00000000000000Copyright (c) 2013, Luke Pomfrey All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. django-debreach-2.0.1/MANIFEST.in0000664000175000017500000000033413342241503021172 0ustar lukepomfreylukepomfrey00000000000000include LICENSE include README.rst include runtests.py recursive-include debreach *.html *.png *.gif *js *jpg *jpeg *svg *py recursive-include docs *.rst *.py make.bat Makefile recursive-include test_project *.py *.html django-debreach-2.0.1/PKG-INFO0000664000175000017500000000174513547572542020561 0ustar lukepomfreylukepomfrey00000000000000Metadata-Version: 1.1 Name: django-debreach Version: 2.0.1 Summary: Adds middleware to give some added protection against the BREACH attack in Django. Home-page: http://github.com/lpomfrey/django-debreach Author: Luke Pomfrey Author-email: lpomfrey@gmail.com License: BSD Description: UNKNOWN Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Operating System :: OS Independent Classifier: Framework :: Django Classifier: Framework :: Django :: 2.2 Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Topic :: Internet :: WWW/HTTP django-debreach-2.0.1/README.rst0000644000175000017500000000450013547562237021141 0ustar lukepomfreylukepomfrey00000000000000django-debreach =============== Basic/extra mitigation against the `BREACH attack `_ for Django projects. django-debreach provides additional protection to Django's built in CSRF token masking by randomising the content length of each response. This is acheived by adding a random string of between 12 and 25 characters as a comment to the end of the HTML content. Note that this will only be applied to responses with a content type of ``text/html``. When combined with rate limiting in your web-server, or by using something like `django-ratelimit `_, the techniques here should provide at least some protection against the BREACH attack. .. image:: https://badge.fury.io/py/django-debreach.png :target: https://badge.fury.io/py/django-debreach :alt: PyPI .. image:: https://travis-ci.org/lpomfrey/django-debreach.png?branch=master :target: https://travis-ci.org/lpomfrey/django-debreach :alt: Build status .. image:: https://coveralls.io/repos/lpomfrey/django-debreach/badge.png?branch=master :target: https://coveralls.io/r/lpomfrey/django-debreach?branch=master :alt: Coverage Installation & Usage -------------------- Install from PyPI using:: $ pip install django-debreach To enable content length modification for all responses, add the ``debreach.middleware.RandomCommentMiddleware`` to the *start* of your middleware, but *after* the ``GzipMiddleware`` if you are using that.:: MIDDLEWARE_CLASSES = ( 'debreach.middleware.RandomCommentMiddleware', ... ) or:: MIDDLEWARE_CLASSES = ( 'django.middleware.gzip.GzipMiddleware', 'debreach.middleware.RandomCommentMiddleware', ... ) If you wish to disable this feature for selected views, simply apply the ``debreach.decorators.random_comment_exempt`` decorator to the view. If you only want to protect a subset of views with content length modification then it may be easier to not use the middleware, but to selectively apply the ``debreach.decorators.append_random_comment`` decorator to the views you want protected. Python 2 and Django < 2.0 support --------------------------------- Version 2.0.0 drops all support for Python 2 and Django < 2.0. If you need support for those versions continue using ``django-debreach>=1.5.2,<2.0``. django-debreach-2.0.1/debreach/0000775000175000017500000000000013547572542021212 5ustar lukepomfreylukepomfrey00000000000000django-debreach-2.0.1/debreach/__init__.py0000664000175000017500000000027513547572451023326 0ustar lukepomfreylukepomfrey00000000000000# -*- coding: utf-8 -*- from distutils import version __version__ = '2.0.1' version_info = version.StrictVersion(__version__).version default_app_config = 'debreach.apps.DebreachConfig' django-debreach-2.0.1/debreach/apps.py0000644000175000017500000000016413547562007022521 0ustar lukepomfreylukepomfrey00000000000000# -*- coding: utf-8 -*- from django.apps import AppConfig class DebreachConfig(AppConfig): name = 'debreach' django-debreach-2.0.1/debreach/decorators.py0000644000175000017500000000157713547572413023736 0ustar lukepomfreylukepomfrey00000000000000# -*- coding: utf-8 -*- from functools import wraps from django.utils.decorators import decorator_from_middleware from debreach.middleware import RandomCommentMiddleware append_random_comment = decorator_from_middleware(RandomCommentMiddleware) append_random_comment.__name__ = str('append_random_comment') append_random_comment.__doc__ = ''' Applies a random comment to the response of the decorated view in the same way as the RandomCommentMiddleware. Using both, or using the decorator multiple times is harmless and efficient. ''' def random_comment_exempt(view_func): """ Marks a view as being exempt from having its response modified by the RandomCommentMiddleware """ def wrapped_view(*args, **kwargs): response = view_func(*args, **kwargs) response._random_comment_exempt = True return response return wraps(view_func)(wrapped_view) django-debreach-2.0.1/debreach/middleware.py0000644000175000017500000000217113547561647023704 0ustar lukepomfreylukepomfrey00000000000000# -*- coding: utf-8 -*- import logging import random from django.utils.crypto import get_random_string from django.utils.deprecation import MiddlewareMixin from django.utils.encoding import force_str log = logging.getLogger(__name__) class RandomCommentMiddleware(MiddlewareMixin): def process_response(self, request, response): if not getattr(response, 'streaming', False) \ and response.get('Content-Type', '').startswith('text/html') \ and response.content \ and isinstance(response.content, (bytes, str)) \ and not getattr(response, '_random_comment_exempt', False) \ and not getattr(response, '_random_comment_applied', False): comment = ''.format( get_random_string(random.choice(range(12, 25)))) response.content = '{0}{1}'.format( force_str(response.content), comment) response._random_comment_applied = True if response.has_header('Content-Length'): response['Content-Length'] = str(len(response.content)) return response django-debreach-2.0.1/debreach/tests.py0000644000175000017500000001013013547562030022706 0ustar lukepomfreylukepomfrey00000000000000# -*- coding: utf-8 -*- import os import unittest from django.http import HttpResponse from django.test import TestCase from django.test.client import RequestFactory from django.urls import reverse from django.utils.encoding import force_str from debreach.decorators import append_random_comment, random_comment_exempt from debreach.middleware import RandomCommentMiddleware def test_view(request): return HttpResponse() class TestRandomCommentMiddleware(TestCase): def test_noop_on_wrong_content_type(self): response = HttpResponse('abc', content_type='text/plain') request = RequestFactory().get('/') middleware = RandomCommentMiddleware() response = middleware.process_response(request, response) self.assertEqual(response.content, b'abc') def test_html_content_type(self): html = ''' Page title

Test

Lorem ipsum

''' response = HttpResponse(html, content_type='text/html') request = RequestFactory().get('/') middleware = RandomCommentMiddleware() response = middleware.process_response(request, response) self.assertNotEqual(response.content, html) def test_unicode_characters(self): html = ''' Page title

Test

{0}

'''.format(''.join(chr(x) for x in range(9999))) response = HttpResponse(html, content_type='text/html') request = RequestFactory().get('/') middleware = RandomCommentMiddleware() response = middleware.process_response(request, response) self.assertNotEqual(force_str(response.content), force_str(html)) def test_exemption(self): html = ''' Test

Test body.

''' response = HttpResponse(html) response._random_comment_exempt = True request = RequestFactory().get('/') middleware = RandomCommentMiddleware() response = middleware.process_response(request, response) self.assertEqual(force_str(response.content), html) def test_missing_content_type(self): request = RequestFactory().get('/') response = HttpResponse('') del response['Content-Type'] middleware = RandomCommentMiddleware() processed_response = middleware.process_response(request, response) self.assertEqual(response, processed_response) def test_empty_response_body_ignored(self): request = RequestFactory().get('/') response = HttpResponse('') middleware = RandomCommentMiddleware() processed_response = middleware.process_response(request, response) self.assertEqual(len(processed_response.content), 0) class TestDecorators(TestCase): def test_append_random_comment(self): html = ''' Test

Test body.

''' @append_random_comment def test_view(request): return HttpResponse(html) request = RequestFactory().get('/') response = test_view(request) self.assertNotEqual(force_str(response.content), html) self.assertIn('', force_str(response.content)) def test_random_comment_exempt(self): html = ''' Test

Test body.

''' @random_comment_exempt def test_view(request): return HttpResponse(html) request = RequestFactory().get('/') response = test_view(request) self.assertTrue(response._random_comment_exempt) @unittest.skipUnless( 'test_project' in os.environ.get('DJANGO_SETTINGS_MODULE', ''), 'Not running in test_project' ) class IntegrationTests(TestCase): def test_adds_comment(self): resp = self.client.get(reverse('home')) self.assertFalse(resp.content.endswith(b'')) django-debreach-2.0.1/django_debreach.egg-info/0000775000175000017500000000000013547572542024226 5ustar lukepomfreylukepomfrey00000000000000django-debreach-2.0.1/django_debreach.egg-info/PKG-INFO0000644000175000017500000000174513547572541025327 0ustar lukepomfreylukepomfrey00000000000000Metadata-Version: 1.1 Name: django-debreach Version: 2.0.1 Summary: Adds middleware to give some added protection against the BREACH attack in Django. Home-page: http://github.com/lpomfrey/django-debreach Author: Luke Pomfrey Author-email: lpomfrey@gmail.com License: BSD Description: UNKNOWN Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Operating System :: OS Independent Classifier: Framework :: Django Classifier: Framework :: Django :: 2.2 Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Topic :: Internet :: WWW/HTTP django-debreach-2.0.1/django_debreach.egg-info/SOURCES.txt0000644000175000017500000000104113547572541026103 0ustar lukepomfreylukepomfrey00000000000000LICENSE MANIFEST.in README.rst runtests.py setup.py debreach/__init__.py debreach/apps.py debreach/decorators.py debreach/middleware.py debreach/tests.py django_debreach.egg-info/PKG-INFO django_debreach.egg-info/SOURCES.txt django_debreach.egg-info/dependency_links.txt django_debreach.egg-info/top_level.txt docs/Makefile docs/conf.py docs/index.rst docs/make.bat test_project/__init__.py test_project/forms.py test_project/settings.py test_project/urls.py test_project/wsgi.py test_project/templates/home.html test_project/templates/test.htmldjango-debreach-2.0.1/django_debreach.egg-info/dependency_links.txt0000644000175000017500000000000113547572541030271 0ustar lukepomfreylukepomfrey00000000000000 django-debreach-2.0.1/django_debreach.egg-info/top_level.txt0000644000175000017500000000001113547572541026745 0ustar lukepomfreylukepomfrey00000000000000debreach django-debreach-2.0.1/docs/0000775000175000017500000000000013547572542020405 5ustar lukepomfreylukepomfrey00000000000000django-debreach-2.0.1/docs/Makefile0000644000175000017500000001274012644500521022030 0ustar lukepomfreylukepomfrey00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/django-debreach.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django-debreach.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/django-debreach" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django-debreach" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." django-debreach-2.0.1/docs/conf.py0000644000175000017500000002212512644500521021665 0ustar lukepomfreylukepomfrey00000000000000# -*- coding: utf-8 -*- # # django-debreach documentation build configuration file, created by # sphinx-quickstart on Mon Sep 2 16:08:48 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import re import sys from distutils import version init_py = open('../debreach/__init__.py').read() version_string = re.search( '^__version__ = [\'"]([^\'"]+)[\'"]', init_py, re.MULTILINE).group(1) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'django-debreach' copyright = u'2013, Luke Pomfrey' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # version = u'{0}'.format(version.StrictVersion(version_string)) # The full version, including alpha/beta/rc tags. release = version_string # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'django-debreachdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'django-debreach.tex', u'django-debreach Documentation', u'Luke Pomfrey', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'django-debreach', u'django-debreach Documentation', [u'Luke Pomfrey'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'django-debreach', u'django-debreach Documentation', u'Luke Pomfrey', 'django-debreach', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # -- Options for Epub output --------------------------------------------------- # Bibliographic Dublin Core info. epub_title = u'django-debreach' epub_author = u'Luke Pomfrey' epub_publisher = u'Luke Pomfrey' epub_copyright = u'2013, Luke Pomfrey' # The language of the text. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # A tuple containing the cover image and cover page html template filenames. #epub_cover = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. #epub_exclude_files = [] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True django-debreach-2.0.1/docs/index.rst0000644000175000017500000000450013547562237022243 0ustar lukepomfreylukepomfrey00000000000000django-debreach =============== Basic/extra mitigation against the `BREACH attack `_ for Django projects. django-debreach provides additional protection to Django's built in CSRF token masking by randomising the content length of each response. This is acheived by adding a random string of between 12 and 25 characters as a comment to the end of the HTML content. Note that this will only be applied to responses with a content type of ``text/html``. When combined with rate limiting in your web-server, or by using something like `django-ratelimit `_, the techniques here should provide at least some protection against the BREACH attack. .. image:: https://badge.fury.io/py/django-debreach.png :target: https://badge.fury.io/py/django-debreach :alt: PyPI .. image:: https://travis-ci.org/lpomfrey/django-debreach.png?branch=master :target: https://travis-ci.org/lpomfrey/django-debreach :alt: Build status .. image:: https://coveralls.io/repos/lpomfrey/django-debreach/badge.png?branch=master :target: https://coveralls.io/r/lpomfrey/django-debreach?branch=master :alt: Coverage Installation & Usage -------------------- Install from PyPI using:: $ pip install django-debreach To enable content length modification for all responses, add the ``debreach.middleware.RandomCommentMiddleware`` to the *start* of your middleware, but *after* the ``GzipMiddleware`` if you are using that.:: MIDDLEWARE_CLASSES = ( 'debreach.middleware.RandomCommentMiddleware', ... ) or:: MIDDLEWARE_CLASSES = ( 'django.middleware.gzip.GzipMiddleware', 'debreach.middleware.RandomCommentMiddleware', ... ) If you wish to disable this feature for selected views, simply apply the ``debreach.decorators.random_comment_exempt`` decorator to the view. If you only want to protect a subset of views with content length modification then it may be easier to not use the middleware, but to selectively apply the ``debreach.decorators.append_random_comment`` decorator to the views you want protected. Python 2 and Django < 2.0 support --------------------------------- Version 2.0.0 drops all support for Python 2 and Django < 2.0. If you need support for those versions continue using ``django-debreach>=1.5.2,<2.0``. django-debreach-2.0.1/docs/make.bat0000644000175000017500000001177212644500521022001 0ustar lukepomfreylukepomfrey00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\django-debreach.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\django-debreach.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end django-debreach-2.0.1/runtests.py0000644000175000017500000000077413216770041021707 0ustar lukepomfreylukepomfrey00000000000000# -*- coding: utf-8 -*- from __future__ import unicode_literals import os import sys import django os.environ['PYTHONPATH'] = os.path.dirname(__file__) os.environ['DJANGO_SETTINGS_MODULE'] = 'test_project.settings' def runtests(): django.setup() from django.conf import settings from django.test.utils import get_runner test_runner = get_runner(settings)(verbosity=2) failures = test_runner.run_tests(['debreach']) sys.exit(failures) if __name__ == '__main__': runtests() django-debreach-2.0.1/setup.cfg0000664000175000017500000000004613547572542021276 0ustar lukepomfreylukepomfrey00000000000000[egg_info] tag_build = tag_date = 0 django-debreach-2.0.1/setup.py0000644000175000017500000000377513547564240021175 0ustar lukepomfreylukepomfrey00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import os import re import sys from setuptools import setup, find_packages def get_version(package): ''' Return package version as listed in `__version__` in `init.py`. ''' init_py = open(os.path.join(package, '__init__.py')).read() return re.search( '^__version__ = [\'"]([^\'"]+)[\'"]', init_py, re.MULTILINE ).group(1) version = get_version('debreach') _PUBLISH_WARNING = ''' ****************** !!! DEPRECATED !!! ****************** Use twine to publish packages to pypi now. Ensure you have the `wheel` and `twine` packages installed with pip install wheel twine Then create some distributions like python setup.py sdist bdist_wheel Then upload with twine twine upload dist/* ''' if sys.argv[-1] == 'publish': print(_PUBLISH_WARNING) sys.exit() setup( name='django-debreach', version=version, url='http://github.com/lpomfrey/django-debreach', license='BSD', description='Adds middleware to give some added protection against the ' 'BREACH attack in Django.', author='Luke Pomfrey', author_email='lpomfrey@gmail.com', packages=find_packages(exclude=('test_project', 'docs')), install_requires=[], tests_require=[ 'django', ], test_suite='runtests.runtests', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Framework :: Django', 'Framework :: Django :: 2.2', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Internet :: WWW/HTTP' ] ) django-debreach-2.0.1/test_project/0000775000175000017500000000000013547572542022162 5ustar lukepomfreylukepomfrey00000000000000django-debreach-2.0.1/test_project/__init__.py0000644000175000017500000000000012644500521024240 0ustar lukepomfreylukepomfrey00000000000000django-debreach-2.0.1/test_project/forms.py0000644000175000017500000000023112644500521023635 0ustar lukepomfreylukepomfrey00000000000000# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms class TestForm(forms.Form): message = forms.CharField() django-debreach-2.0.1/test_project/settings.py0000644000175000017500000001172112753576723024377 0ustar lukepomfreylukepomfrey00000000000000# Django settings for test_project project. import os import django DIRNAME = os.path.dirname(__file__) DEBUG = True if django.VERSION >= (1, 6): TEST_RUNNER = 'django.test.runner.DiscoverRunner' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = [] # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # In a Windows environment this must be set to your system time zone. TIME_ZONE = 'Europe/London' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-gb' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = False # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/var/www/example.com/media/" MEDIA_ROOT = os.path.join(DIRNAME, 'media/') # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://example.com/media/", "http://media.example.com/" MEDIA_URL = '/media/' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/var/www/example.com/static/" STATIC_ROOT = os.path.join(DIRNAME, 'static/') # URL prefix for static files. # Example: "http://example.com/static/", "http://static.example.com/" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = ')o3o4cx2t*ppdacgd571pi$97y8*jlihy8)qoto-$t5_-6bw9j' if django.VERSION < (1, 10): MIDDLEWARE_CLASSES = ( 'debreach.middleware.CSRFCryptMiddleware', 'debreach.middleware.RandomCommentMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) _TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', 'django.contrib.messages.context_processors.messages', 'debreach.context_processors.csrf', ) else: MIDDLEWARE_CLASSES = ( 'debreach.middleware.RandomCommentMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) _TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.contrib.messages.context_processors.messages', ) ROOT_URLCONF = 'test_project.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'test_project.wsgi.application' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'DIRS': [ os.path.join(os.path.dirname(__file__), 'templates/'), ], 'OPTIONS': { 'context_processors': _TEMPLATE_CONTEXT_PROCESSORS, } }, ] INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.staticfiles', 'debreach', ) django-debreach-2.0.1/test_project/templates/0000775000175000017500000000000013547572542024160 5ustar lukepomfreylukepomfrey00000000000000django-debreach-2.0.1/test_project/templates/home.html0000644000175000017500000000024512644500521025756 0ustar lukepomfreylukepomfrey00000000000000 Home

Home

Lorem ipsum blah blerg

django-debreach-2.0.1/test_project/templates/test.html0000644000175000017500000000044112644500521026003 0ustar lukepomfreylukepomfrey00000000000000 Test

Test

{{ form.as_p }} {% csrf_token %}
django-debreach-2.0.1/test_project/urls.py0000644000175000017500000000177012753575715023527 0ustar lukepomfreylukepomfrey00000000000000# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import url from django.views.generic.base import TemplateView from django.views.generic.edit import FormView from test_project.forms import TestForm # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = [ # Examples: # url(r'^$', 'test_project.views.home', name='home'), # url(r'^test_project/', include('test_project.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'), url( r'^form/$', FormView.as_view( form_class=TestForm, template_name='test.html', success_url='/'), name='test_form' ), ] django-debreach-2.0.1/test_project/wsgi.py0000644000175000017500000000263512644500521023472 0ustar lukepomfreylukepomfrey00000000000000""" WSGI config for test_project project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "test_project.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_project.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)