Django: security middleware is crashing the site

By | December 7, 2017
Questions:

On production, I’ve been trying to add the djangosecure.middleware.SecurityMiddleware (from http://pypi.python.org/pypi/django-secure)to my settings, but haven’t had any luck making it work.

When I run:

./manage.py checksecure

Everything passes perfectly fine. But I’m unable to load the site up. It gives me the following error:

The webpage has resulted in too many redirects. Clearing your cookies for this site or 
allowing third-party cookies may fix the problem. If not, it is possibly a server 
configuration issue and not a problem with your computer.

Locally, when I use the production settings I receive a page error with:

Unable to make a secure connection to the server. This may be a problem with the server,
or it may be requiring a client authentication certificate that you don't have.

My terminal then gets filled with strange errors that I can’t decipher:

[12/Jan/2013 14:15:25] code 400, message Bad HTTP/0.9 request type    
('\x16\x03\x01\x00\x98\x01\x00\x00\x94\x03\x02P\xf1\xc4]\x97e\xdd\xdc\xa9\xeb\x0e\xfc\xbb\xfa3 ')
[12/Jan/2013 14:15:25] "??P??]?e?ܩ????3 Ʀ?-?:?.E:?o?FH?" 400 -
[12/Jan/2013 14:15:25] code 400, message Bad request syntax     ('\x16\x03\x01\x00\x98\x01\x00\x00\x94\x03\x02P\xf1\xc4]M\xeeA50\xfc\x15%\xc1\xa4\x02\xec\xf0\x1fO')
[12/Jan/2013 14:15:25] "??P??]M?A50?%????O" 400 -
[12/Jan/2013 14:15:25] code 400, message Bad request syntax ('\x16\x03\x01\x00\x98\x01\x00\x00\x94\x03\x01P\xf1\xc4]\x8eg\xbey\x155\xafiP5\x85r\xb4|\x8c\x

Any advice?

Answers:

Infinite-redirects means you have set SECURE_SSL_REDIRECT to True, but in production your site runs behind an SSL-stripping proxy server, so Django can’t tell that the request is already in fact SSL, so it continually tries to redirect to SSL. As noted in the linked docs, you need to figure out what header your proxy sets to indicate an externally-SSL request, and set the SECURE_PROXY_SSL_HEADER setting accordingly.

Using the production settings locally will not work because Django’s development server does not support SSL. The strange terminal output is your browser trying to make an SSL handshake with a server that doesn’t understand SSL.

Leave a Reply

Your email address will not be published. Required fields are marked *