Skip to content

Commit

Permalink
Add support for the X-XSS-Protection and X-Content-Type-Options headers.
Browse files Browse the repository at this point in the history
* Add the X-XSS-Protection header to prevent simple XSS attacks
  and enforce the blocking (rather than the rewriting) mode.

* Add the X-Content-Type-Options header to prevent browsers sniffing
  the MIME type away from the declared Content-Type.
  • Loading branch information
reedloden committed Sep 9, 2012
1 parent e2e02ad commit 8bf0fa6
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
2 changes: 2 additions & 0 deletions commonware/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,6 @@
from commonware.request.middleware import SetRemoteAddrFromForwardedFor
from commonware.response.middleware import FrameOptionsHeader
from commonware.response.middleware import StrictTransportMiddleware
from commonware.response.middleware import XSSProtectionHeader
from commonware.response.middleware import ContentTypeOptionsHeader
from commonware.session.middleware import NoVarySessionMiddleware
20 changes: 20 additions & 0 deletions commonware/response/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,23 @@ def process_response(self, request, response):
val += '; includeSubDomains'
response['Strict-Transport-Security'] = val
return response


class XSSProtectionHeader(object):
"""
Set the X-XSS-Protection header on responses.
"""

def process_response(self, request, response):
response['x-xss-protection'] = '1; mode=block'
return response


class ContentTypeOptionsHeader(object):
"""
Set the X-Content-Type-Options header on responses.
"""

def process_response(self, request, response):
response['x-content-type-options'] = 'nosniff'
return response
12 changes: 12 additions & 0 deletions commonware/response/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,15 @@ def test_xframe_middleware_disable():
resp.no_frame_options = True
resp = mw.process_response({}, resp)
assert not 'x-frame-options' in resp


def test_xssprotection_middleware():
resp = _make_resp(middleware.XSSProtectionHeader)
assert 'x-xss-protection' in resp
eq_('1; mode=block', resp['x-xss-protection'])


def test_contenttypeoptions_middleware():
resp = _make_resp(middleware.ContentTypeOptionsHeader)
assert 'x-content-type-options' in resp
eq_('nosniff', resp['x-content-type-options'])

0 comments on commit 8bf0fa6

Please sign in to comment.