änderung1
This commit is contained in:
1 parent
cc1d096bc3
commit
cbdda613b7
2098 files changed
+274524
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,173 @@
|
||||
import re
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.core.mail import mail_managers
|
||||
from django.http import HttpResponsePermanentRedirect
|
||||
from django.urls import is_valid_path
|
||||
from django.utils.deprecation import MiddlewareMixin
|
||||
from django.utils.http import escape_leading_slashes
|
||||
|
||||
|
||||
class CommonMiddleware(MiddlewareMixin):
|
||||
"""
|
||||
"Common" middleware for taking care of some basic operations:
|
||||
|
||||
- Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS
|
||||
|
||||
- URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings,
|
||||
append missing slashes and/or prepends missing "www."s.
|
||||
|
||||
- If APPEND_SLASH is set and the initial URL doesn't end with a
|
||||
slash, and it is not found in urlpatterns, form a new URL by
|
||||
appending a slash at the end. If this new URL is found in
|
||||
urlpatterns, return an HTTP redirect to this new URL; otherwise
|
||||
process the initial URL as usual.
|
||||
|
||||
This behavior can be customized by subclassing CommonMiddleware and
|
||||
overriding the response_redirect_class attribute.
|
||||
"""
|
||||
|
||||
response_redirect_class = HttpResponsePermanentRedirect
|
||||
|
||||
def process_request(self, request):
|
||||
"""
|
||||
Check for denied User-Agents and rewrite the URL based on
|
||||
settings.APPEND_SLASH and settings.PREPEND_WWW
|
||||
"""
|
||||
|
||||
# Check for denied User-Agents
|
||||
if 'HTTP_USER_AGENT' in request.META:
|
||||
for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
|
||||
if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
|
||||
raise PermissionDenied('Forbidden user agent')
|
||||
|
||||
# Check for a redirect based on settings.PREPEND_WWW
|
||||
host = request.get_host()
|
||||
must_prepend = settings.PREPEND_WWW and host and not host.startswith('www.')
|
||||
redirect_url = ('%s://www.%s' % (request.scheme, host)) if must_prepend else ''
|
||||
|
||||
# Check if a slash should be appended
|
||||
if self.should_redirect_with_slash(request):
|
||||
path = self.get_full_path_with_slash(request)
|
||||
else:
|
||||
path = request.get_full_path()
|
||||
|
||||
# Return a redirect if necessary
|
||||
if redirect_url or path != request.get_full_path():
|
||||
redirect_url += path
|
||||
return self.response_redirect_class(redirect_url)
|
||||
|
||||
def should_redirect_with_slash(self, request):
|
||||
"""
|
||||
Return True if settings.APPEND_SLASH is True and appending a slash to
|
||||
the request path turns an invalid path into a valid one.
|
||||
"""
|
||||
if settings.APPEND_SLASH and not request.path_info.endswith('/'):
|
||||
urlconf = getattr(request, 'urlconf', None)
|
||||
return (
|
||||
not is_valid_path(request.path_info, urlconf) and
|
||||
is_valid_path('%s/' % request.path_info, urlconf)
|
||||
)
|
||||
return False
|
||||
|
||||
def get_full_path_with_slash(self, request):
|
||||
"""
|
||||
Return the full path of the request with a trailing slash appended.
|
||||
|
||||
Raise a RuntimeError if settings.DEBUG is True and request.method is
|
||||
POST, PUT, or PATCH.
|
||||
"""
|
||||
new_path = request.get_full_path(force_append_slash=True)
|
||||
# Prevent construction of scheme relative urls.
|
||||
new_path = escape_leading_slashes(new_path)
|
||||
if settings.DEBUG and request.method in ('POST', 'PUT', 'PATCH'):
|
||||
raise RuntimeError(
|
||||
"You called this URL via %(method)s, but the URL doesn't end "
|
||||
"in a slash and you have APPEND_SLASH set. Django can't "
|
||||
"redirect to the slash URL while maintaining %(method)s data. "
|
||||
"Change your form to point to %(url)s (note the trailing "
|
||||
"slash), or set APPEND_SLASH=False in your Django settings." % {
|
||||
'method': request.method,
|
||||
'url': request.get_host() + new_path,
|
||||
}
|
||||
)
|
||||
return new_path
|
||||
|
||||
def process_response(self, request, response):
|
||||
"""
|
||||
When the status code of the response is 404, it may redirect to a path
|
||||
with an appended slash if should_redirect_with_slash() returns True.
|
||||
"""
|
||||
# If the given URL is "Not Found", then check if we should redirect to
|
||||
# a path with a slash appended.
|
||||
if response.status_code == 404:
|
||||
if self.should_redirect_with_slash(request):
|
||||
return self.response_redirect_class(self.get_full_path_with_slash(request))
|
||||
|
||||
# Add the Content-Length header to non-streaming responses if not
|
||||
# already set.
|
||||
if not response.streaming and not response.has_header('Content-Length'):
|
||||
response['Content-Length'] = str(len(response.content))
|
||||
|
||||
return response
|
||||
|
||||
|
||||
class BrokenLinkEmailsMiddleware(MiddlewareMixin):
|
||||
|
||||
def process_response(self, request, response):
|
||||
"""Send broken link emails for relevant 404 NOT FOUND responses."""
|
||||
if response.status_code == 404 and not settings.DEBUG:
|
||||
domain = request.get_host()
|
||||
path = request.get_full_path()
|
||||
referer = request.META.get('HTTP_REFERER', '')
|
||||
|
||||
if not self.is_ignorable_request(request, path, domain, referer):
|
||||
ua = request.META.get('HTTP_USER_AGENT', '<none>')
|
||||
ip = request.META.get('REMOTE_ADDR', '<none>')
|
||||
mail_managers(
|
||||
"Broken %slink on %s" % (
|
||||
('INTERNAL ' if self.is_internal_request(domain, referer) else ''),
|
||||
domain
|
||||
),
|
||||
"Referrer: %s\nRequested URL: %s\nUser agent: %s\n"
|
||||
"IP address: %s\n" % (referer, path, ua, ip),
|
||||
fail_silently=True,
|
||||
)
|
||||
return response
|
||||
|
||||
def is_internal_request(self, domain, referer):
|
||||
"""
|
||||
Return True if the referring URL is the same domain as the current
|
||||
request.
|
||||
"""
|
||||
# Different subdomains are treated as different domains.
|
||||
return bool(re.match("^https?://%s/" % re.escape(domain), referer))
|
||||
|
||||
def is_ignorable_request(self, request, uri, domain, referer):
|
||||
"""
|
||||
Return True if the given request *shouldn't* notify the site managers
|
||||
according to project settings or in situations outlined by the inline
|
||||
comments.
|
||||
"""
|
||||
# The referer is empty.
|
||||
if not referer:
|
||||
return True
|
||||
|
||||
# APPEND_SLASH is enabled and the referer is equal to the current URL
|
||||
# without a trailing slash indicating an internal redirect.
|
||||
if settings.APPEND_SLASH and uri.endswith('/') and referer == uri[:-1]:
|
||||
return True
|
||||
|
||||
# A '?' in referer is identified as a search engine source.
|
||||
if not self.is_internal_request(domain, referer) and '?' in referer:
|
||||
return True
|
||||
|
||||
# The referer is equal to the current URL, ignoring the scheme (assumed
|
||||
# to be a poorly implemented bot).
|
||||
parsed_referer = urlparse(referer)
|
||||
if parsed_referer.netloc in ['', domain] and parsed_referer.path == uri:
|
||||
return True
|
||||
|
||||
return any(pattern.search(uri) for pattern in settings.IGNORABLE_404_URLS)
|
||||
@@ -0,0 +1,327 @@
|
||||
"""
|
||||
Cross Site Request Forgery Middleware.
|
||||
|
||||
This module provides a middleware that implements protection
|
||||
against request forgeries from other sites.
|
||||
"""
|
||||
import logging
|
||||
import re
|
||||
import string
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import DisallowedHost, ImproperlyConfigured
|
||||
from django.urls import get_callable
|
||||
from django.utils.cache import patch_vary_headers
|
||||
from django.utils.crypto import constant_time_compare, get_random_string
|
||||
from django.utils.deprecation import MiddlewareMixin
|
||||
from django.utils.http import is_same_domain
|
||||
from django.utils.log import log_response
|
||||
|
||||
logger = logging.getLogger('django.security.csrf')
|
||||
|
||||
REASON_NO_REFERER = "Referer checking failed - no Referer."
|
||||
REASON_BAD_REFERER = "Referer checking failed - %s does not match any trusted origins."
|
||||
REASON_NO_CSRF_COOKIE = "CSRF cookie not set."
|
||||
REASON_BAD_TOKEN = "CSRF token missing or incorrect."
|
||||
REASON_MALFORMED_REFERER = "Referer checking failed - Referer is malformed."
|
||||
REASON_INSECURE_REFERER = "Referer checking failed - Referer is insecure while host is secure."
|
||||
|
||||
CSRF_SECRET_LENGTH = 32
|
||||
CSRF_TOKEN_LENGTH = 2 * CSRF_SECRET_LENGTH
|
||||
CSRF_ALLOWED_CHARS = string.ascii_letters + string.digits
|
||||
CSRF_SESSION_KEY = '_csrftoken'
|
||||
|
||||
|
||||
def _get_failure_view():
|
||||
"""Return the view to be used for CSRF rejections."""
|
||||
return get_callable(settings.CSRF_FAILURE_VIEW)
|
||||
|
||||
|
||||
def _get_new_csrf_string():
|
||||
return get_random_string(CSRF_SECRET_LENGTH, allowed_chars=CSRF_ALLOWED_CHARS)
|
||||
|
||||
|
||||
def _salt_cipher_secret(secret):
|
||||
"""
|
||||
Given a secret (assumed to be a string of CSRF_ALLOWED_CHARS), generate a
|
||||
token by adding a salt and using it to encrypt the secret.
|
||||
"""
|
||||
salt = _get_new_csrf_string()
|
||||
chars = CSRF_ALLOWED_CHARS
|
||||
pairs = zip((chars.index(x) for x in secret), (chars.index(x) for x in salt))
|
||||
cipher = ''.join(chars[(x + y) % len(chars)] for x, y in pairs)
|
||||
return salt + cipher
|
||||
|
||||
|
||||
def _unsalt_cipher_token(token):
|
||||
"""
|
||||
Given a token (assumed to be a string of CSRF_ALLOWED_CHARS, of length
|
||||
CSRF_TOKEN_LENGTH, and that its first half is a salt), use it to decrypt
|
||||
the second half to produce the original secret.
|
||||
"""
|
||||
salt = token[:CSRF_SECRET_LENGTH]
|
||||
token = token[CSRF_SECRET_LENGTH:]
|
||||
chars = CSRF_ALLOWED_CHARS
|
||||
pairs = zip((chars.index(x) for x in token), (chars.index(x) for x in salt))
|
||||
secret = ''.join(chars[x - y] for x, y in pairs) # Note negative values are ok
|
||||
return secret
|
||||
|
||||
|
||||
def _get_new_csrf_token():
|
||||
return _salt_cipher_secret(_get_new_csrf_string())
|
||||
|
||||
|
||||
def get_token(request):
|
||||
"""
|
||||
Return the CSRF token required for a POST form. The token is an
|
||||
alphanumeric value. A new token is created if one is not already set.
|
||||
|
||||
A side effect of calling this function is to make the csrf_protect
|
||||
decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: Cookie'
|
||||
header to the outgoing response. For this reason, you may need to use this
|
||||
function lazily, as is done by the csrf context processor.
|
||||
"""
|
||||
if "CSRF_COOKIE" not in request.META:
|
||||
csrf_secret = _get_new_csrf_string()
|
||||
request.META["CSRF_COOKIE"] = _salt_cipher_secret(csrf_secret)
|
||||
else:
|
||||
csrf_secret = _unsalt_cipher_token(request.META["CSRF_COOKIE"])
|
||||
request.META["CSRF_COOKIE_USED"] = True
|
||||
return _salt_cipher_secret(csrf_secret)
|
||||
|
||||
|
||||
def rotate_token(request):
|
||||
"""
|
||||
Change the CSRF token in use for a request - should be done on login
|
||||
for security purposes.
|
||||
"""
|
||||
request.META.update({
|
||||
"CSRF_COOKIE_USED": True,
|
||||
"CSRF_COOKIE": _get_new_csrf_token(),
|
||||
})
|
||||
request.csrf_cookie_needs_reset = True
|
||||
|
||||
|
||||
def _sanitize_token(token):
|
||||
# Allow only ASCII alphanumerics
|
||||
if re.search('[^a-zA-Z0-9]', token):
|
||||
return _get_new_csrf_token()
|
||||
elif len(token) == CSRF_TOKEN_LENGTH:
|
||||
return token
|
||||
elif len(token) == CSRF_SECRET_LENGTH:
|
||||
# Older Django versions set cookies to values of CSRF_SECRET_LENGTH
|
||||
# alphanumeric characters. For backwards compatibility, accept
|
||||
# such values as unsalted secrets.
|
||||
# It's easier to salt here and be consistent later, rather than add
|
||||
# different code paths in the checks, although that might be a tad more
|
||||
# efficient.
|
||||
return _salt_cipher_secret(token)
|
||||
return _get_new_csrf_token()
|
||||
|
||||
|
||||
def _compare_salted_tokens(request_csrf_token, csrf_token):
|
||||
# Assume both arguments are sanitized -- that is, strings of
|
||||
# length CSRF_TOKEN_LENGTH, all CSRF_ALLOWED_CHARS.
|
||||
return constant_time_compare(
|
||||
_unsalt_cipher_token(request_csrf_token),
|
||||
_unsalt_cipher_token(csrf_token),
|
||||
)
|
||||
|
||||
|
||||
class CsrfViewMiddleware(MiddlewareMixin):
|
||||
"""
|
||||
Require a present and correct csrfmiddlewaretoken for POST requests that
|
||||
have a CSRF cookie, and set an outgoing CSRF cookie.
|
||||
|
||||
This middleware should be used in conjunction with the {% csrf_token %}
|
||||
template tag.
|
||||
"""
|
||||
# The _accept and _reject methods currently only exist for the sake of the
|
||||
# requires_csrf_token decorator.
|
||||
def _accept(self, request):
|
||||
# Avoid checking the request twice by adding a custom attribute to
|
||||
# request. This will be relevant when both decorator and middleware
|
||||
# are used.
|
||||
request.csrf_processing_done = True
|
||||
return None
|
||||
|
||||
def _reject(self, request, reason):
|
||||
response = _get_failure_view()(request, reason=reason)
|
||||
log_response(
|
||||
'Forbidden (%s): %s', reason, request.path,
|
||||
response=response,
|
||||
request=request,
|
||||
logger=logger,
|
||||
)
|
||||
return response
|
||||
|
||||
def _get_token(self, request):
|
||||
if settings.CSRF_USE_SESSIONS:
|
||||
try:
|
||||
return request.session.get(CSRF_SESSION_KEY)
|
||||
except AttributeError:
|
||||
raise ImproperlyConfigured(
|
||||
'CSRF_USE_SESSIONS is enabled, but request.session is not '
|
||||
'set. SessionMiddleware must appear before CsrfViewMiddleware '
|
||||
'in MIDDLEWARE%s.' % ('_CLASSES' if settings.MIDDLEWARE is None else '')
|
||||
)
|
||||
else:
|
||||
try:
|
||||
cookie_token = request.COOKIES[settings.CSRF_COOKIE_NAME]
|
||||
except KeyError:
|
||||
return None
|
||||
|
||||
csrf_token = _sanitize_token(cookie_token)
|
||||
if csrf_token != cookie_token:
|
||||
# Cookie token needed to be replaced;
|
||||
# the cookie needs to be reset.
|
||||
request.csrf_cookie_needs_reset = True
|
||||
return csrf_token
|
||||
|
||||
def _set_token(self, request, response):
|
||||
if settings.CSRF_USE_SESSIONS:
|
||||
if request.session.get(CSRF_SESSION_KEY) != request.META['CSRF_COOKIE']:
|
||||
request.session[CSRF_SESSION_KEY] = request.META['CSRF_COOKIE']
|
||||
else:
|
||||
response.set_cookie(
|
||||
settings.CSRF_COOKIE_NAME,
|
||||
request.META['CSRF_COOKIE'],
|
||||
max_age=settings.CSRF_COOKIE_AGE,
|
||||
domain=settings.CSRF_COOKIE_DOMAIN,
|
||||
path=settings.CSRF_COOKIE_PATH,
|
||||
secure=settings.CSRF_COOKIE_SECURE,
|
||||
httponly=settings.CSRF_COOKIE_HTTPONLY,
|
||||
samesite=settings.CSRF_COOKIE_SAMESITE,
|
||||
)
|
||||
# Set the Vary header since content varies with the CSRF cookie.
|
||||
patch_vary_headers(response, ('Cookie',))
|
||||
|
||||
def process_request(self, request):
|
||||
csrf_token = self._get_token(request)
|
||||
if csrf_token is not None:
|
||||
# Use same token next time.
|
||||
request.META['CSRF_COOKIE'] = csrf_token
|
||||
|
||||
def process_view(self, request, callback, callback_args, callback_kwargs):
|
||||
if getattr(request, 'csrf_processing_done', False):
|
||||
return None
|
||||
|
||||
# Wait until request.META["CSRF_COOKIE"] has been manipulated before
|
||||
# bailing out, so that get_token still works
|
||||
if getattr(callback, 'csrf_exempt', False):
|
||||
return None
|
||||
|
||||
# Assume that anything not defined as 'safe' by RFC7231 needs protection
|
||||
if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
|
||||
if getattr(request, '_dont_enforce_csrf_checks', False):
|
||||
# Mechanism to turn off CSRF checks for test suite.
|
||||
# It comes after the creation of CSRF cookies, so that
|
||||
# everything else continues to work exactly the same
|
||||
# (e.g. cookies are sent, etc.), but before any
|
||||
# branches that call reject().
|
||||
return self._accept(request)
|
||||
|
||||
if request.is_secure():
|
||||
# Suppose user visits http://example.com/
|
||||
# An active network attacker (man-in-the-middle, MITM) sends a
|
||||
# POST form that targets https://example.com/detonate-bomb/ and
|
||||
# submits it via JavaScript.
|
||||
#
|
||||
# The attacker will need to provide a CSRF cookie and token, but
|
||||
# that's no problem for a MITM and the session-independent
|
||||
# secret we're using. So the MITM can circumvent the CSRF
|
||||
# protection. This is true for any HTTP connection, but anyone
|
||||
# using HTTPS expects better! For this reason, for
|
||||
# https://example.com/ we need additional protection that treats
|
||||
# http://example.com/ as completely untrusted. Under HTTPS,
|
||||
# Barth et al. found that the Referer header is missing for
|
||||
# same-domain requests in only about 0.2% of cases or less, so
|
||||
# we can use strict Referer checking.
|
||||
referer = request.META.get('HTTP_REFERER')
|
||||
if referer is None:
|
||||
return self._reject(request, REASON_NO_REFERER)
|
||||
|
||||
referer = urlparse(referer)
|
||||
|
||||
# Make sure we have a valid URL for Referer.
|
||||
if '' in (referer.scheme, referer.netloc):
|
||||
return self._reject(request, REASON_MALFORMED_REFERER)
|
||||
|
||||
# Ensure that our Referer is also secure.
|
||||
if referer.scheme != 'https':
|
||||
return self._reject(request, REASON_INSECURE_REFERER)
|
||||
|
||||
# If there isn't a CSRF_COOKIE_DOMAIN, require an exact match
|
||||
# match on host:port. If not, obey the cookie rules (or those
|
||||
# for the session cookie, if CSRF_USE_SESSIONS).
|
||||
good_referer = (
|
||||
settings.SESSION_COOKIE_DOMAIN
|
||||
if settings.CSRF_USE_SESSIONS
|
||||
else settings.CSRF_COOKIE_DOMAIN
|
||||
)
|
||||
if good_referer is not None:
|
||||
server_port = request.get_port()
|
||||
if server_port not in ('443', '80'):
|
||||
good_referer = '%s:%s' % (good_referer, server_port)
|
||||
else:
|
||||
try:
|
||||
# request.get_host() includes the port.
|
||||
good_referer = request.get_host()
|
||||
except DisallowedHost:
|
||||
pass
|
||||
|
||||
# Create a list of all acceptable HTTP referers, including the
|
||||
# current host if it's permitted by ALLOWED_HOSTS.
|
||||
good_hosts = list(settings.CSRF_TRUSTED_ORIGINS)
|
||||
if good_referer is not None:
|
||||
good_hosts.append(good_referer)
|
||||
|
||||
if not any(is_same_domain(referer.netloc, host) for host in good_hosts):
|
||||
reason = REASON_BAD_REFERER % referer.geturl()
|
||||
return self._reject(request, reason)
|
||||
|
||||
csrf_token = request.META.get('CSRF_COOKIE')
|
||||
if csrf_token is None:
|
||||
# No CSRF cookie. For POST requests, we insist on a CSRF cookie,
|
||||
# and in this way we can avoid all CSRF attacks, including login
|
||||
# CSRF.
|
||||
return self._reject(request, REASON_NO_CSRF_COOKIE)
|
||||
|
||||
# Check non-cookie token for match.
|
||||
request_csrf_token = ""
|
||||
if request.method == "POST":
|
||||
try:
|
||||
request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
|
||||
except IOError:
|
||||
# Handle a broken connection before we've completed reading
|
||||
# the POST data. process_view shouldn't raise any
|
||||
# exceptions, so we'll ignore and serve the user a 403
|
||||
# (assuming they're still listening, which they probably
|
||||
# aren't because of the error).
|
||||
pass
|
||||
|
||||
if request_csrf_token == "":
|
||||
# Fall back to X-CSRFToken, to make things easier for AJAX,
|
||||
# and possible for PUT/DELETE.
|
||||
request_csrf_token = request.META.get(settings.CSRF_HEADER_NAME, '')
|
||||
|
||||
request_csrf_token = _sanitize_token(request_csrf_token)
|
||||
if not _compare_salted_tokens(request_csrf_token, csrf_token):
|
||||
return self._reject(request, REASON_BAD_TOKEN)
|
||||
|
||||
return self._accept(request)
|
||||
|
||||
def process_response(self, request, response):
|
||||
if not getattr(request, 'csrf_cookie_needs_reset', False):
|
||||
if getattr(response, 'csrf_cookie_set', False):
|
||||
return response
|
||||
|
||||
if not request.META.get("CSRF_COOKIE_USED", False):
|
||||
return response
|
||||
|
||||
# Set the CSRF cookie even if it's already set, so we renew
|
||||
# the expiry timer.
|
||||
self._set_token(request, response)
|
||||
response.csrf_cookie_set = True
|
||||
return response
|
||||
@@ -0,0 +1,52 @@
|
||||
import re
|
||||
|
||||
from django.utils.cache import patch_vary_headers
|
||||
from django.utils.deprecation import MiddlewareMixin
|
||||
from django.utils.text import compress_sequence, compress_string
|
||||
|
||||
re_accepts_gzip = re.compile(r'\bgzip\b')
|
||||
|
||||
|
||||
class GZipMiddleware(MiddlewareMixin):
|
||||
"""
|
||||
Compress content if the browser allows gzip compression.
|
||||
Set the Vary header accordingly, so that caches will base their storage
|
||||
on the Accept-Encoding header.
|
||||
"""
|
||||
def process_response(self, request, response):
|
||||
# It's not worth attempting to compress really short responses.
|
||||
if not response.streaming and len(response.content) < 200:
|
||||
return response
|
||||
|
||||
# Avoid gzipping if we've already got a content-encoding.
|
||||
if response.has_header('Content-Encoding'):
|
||||
return response
|
||||
|
||||
patch_vary_headers(response, ('Accept-Encoding',))
|
||||
|
||||
ae = request.META.get('HTTP_ACCEPT_ENCODING', '')
|
||||
if not re_accepts_gzip.search(ae):
|
||||
return response
|
||||
|
||||
if response.streaming:
|
||||
# Delete the `Content-Length` header for streaming content, because
|
||||
# we won't know the compressed size until we stream it.
|
||||
response.streaming_content = compress_sequence(response.streaming_content)
|
||||
del response['Content-Length']
|
||||
else:
|
||||
# Return the compressed content only if it's actually shorter.
|
||||
compressed_content = compress_string(response.content)
|
||||
if len(compressed_content) >= len(response.content):
|
||||
return response
|
||||
response.content = compressed_content
|
||||
response['Content-Length'] = str(len(response.content))
|
||||
|
||||
# If there is a strong ETag, make it weak to fulfill the requirements
|
||||
# of RFC 7232 section-2.1 while also allowing conditional request
|
||||
# matches on ETags.
|
||||
etag = response.get('ETag')
|
||||
if etag and etag.startswith('"'):
|
||||
response['ETag'] = 'W/' + etag
|
||||
response['Content-Encoding'] = 'gzip'
|
||||
|
||||
return response
|
||||
@@ -0,0 +1,46 @@
|
||||
import re
|
||||
|
||||
from django.conf import settings
|
||||
from django.http import HttpResponsePermanentRedirect
|
||||
from django.utils.deprecation import MiddlewareMixin
|
||||
|
||||
|
||||
class SecurityMiddleware(MiddlewareMixin):
|
||||
def __init__(self, get_response=None):
|
||||
self.sts_seconds = settings.SECURE_HSTS_SECONDS
|
||||
self.sts_include_subdomains = settings.SECURE_HSTS_INCLUDE_SUBDOMAINS
|
||||
self.sts_preload = settings.SECURE_HSTS_PRELOAD
|
||||
self.content_type_nosniff = settings.SECURE_CONTENT_TYPE_NOSNIFF
|
||||
self.xss_filter = settings.SECURE_BROWSER_XSS_FILTER
|
||||
self.redirect = settings.SECURE_SSL_REDIRECT
|
||||
self.redirect_host = settings.SECURE_SSL_HOST
|
||||
self.redirect_exempt = [re.compile(r) for r in settings.SECURE_REDIRECT_EXEMPT]
|
||||
self.get_response = get_response
|
||||
|
||||
def process_request(self, request):
|
||||
path = request.path.lstrip("/")
|
||||
if (self.redirect and not request.is_secure() and
|
||||
not any(pattern.search(path)
|
||||
for pattern in self.redirect_exempt)):
|
||||
host = self.redirect_host or request.get_host()
|
||||
return HttpResponsePermanentRedirect(
|
||||
"https://%s%s" % (host, request.get_full_path())
|
||||
)
|
||||
|
||||
def process_response(self, request, response):
|
||||
if (self.sts_seconds and request.is_secure() and
|
||||
'Strict-Transport-Security' not in response):
|
||||
sts_header = "max-age=%s" % self.sts_seconds
|
||||
if self.sts_include_subdomains:
|
||||
sts_header = sts_header + "; includeSubDomains"
|
||||
if self.sts_preload:
|
||||
sts_header = sts_header + "; preload"
|
||||
response['Strict-Transport-Security'] = sts_header
|
||||
|
||||
if self.content_type_nosniff:
|
||||
response.setdefault('X-Content-Type-Options', 'nosniff')
|
||||
|
||||
if self.xss_filter:
|
||||
response.setdefault('X-XSS-Protection', '1; mode=block')
|
||||
|
||||
return response
|
||||
Reference in new issue
Block a user