def process_response(self, request, response): if not getattr(response, 'streaming', False) \ and response['Content-Type'] == 'text/html' \ and isinstance(response.content, string_types): comment = '<!-- {0} -->'.format( get_random_string(random.choice(range(12, 25)))) response.content = '{0}{1}'.format( force_text(response.content), comment) return response
def process_response(self, request, response): str_types = string_types + (binary_type,) if ( not getattr(response, "streaming", False) and response.get("Content-Type", "").startswith("text/html") and response.content and isinstance(response.content, str_types) and not getattr(response, "_random_comment_exempt", False) ): comment = "<!-- {0} -->".format(get_random_string(random.choice(range(12, 25)))) response.content = "{0}{1}".format(force_text(response.content), comment) return response
def _get_val(): token = get_token(request) if token is None: # In order to be able to provide debugging info in the # case of misconfiguration, we use a sentinel value # instead of returning an empty dict. return 'NOTPROVIDED' else: key = base64.encodestring(get_random_string(16)).strip() aes = AES.new(key) padding = ''.join(' ' for x in range(16 - (len(token) % 16))) value = base64.encodestring( aes.encrypt('{0}{1}'.format(token, padding))).strip() token = '$'.join((key, value)) return smart_text(token)
def _get_val(): token = get_token(request) if token is None: # In order to be able to provide debugging info in the # case of misconfiguration, we use a sentinel value # instead of returning an empty dict. return 'NOTPROVIDED' else: key = force_bytes(get_random_string(16)) aes = AES.new(key) pad_length = 16 - (len(token) % 16 or 16) padding = ''.join('#' for _ in range(pad_length)) value = base64.b64encode( aes.encrypt('{0}{1}'.format(token, padding)) ) token = '$'.join((force_text(key), force_text(value))) return force_text(token)
def test_round_trip_loop(self): ''' Checks a wide range of input tokens and keys ''' for _ in range(1000): request = RequestFactory().get('/') csrf_token = get_random_string(32) request.META['CSRF_COOKIE'] = csrf_token token = force_text(csrf(request)['csrf_token']) request = RequestFactory().post( '/', {'csrfmiddlewaretoken': token}) middleware = CSRFCryptMiddleware() middleware.process_request(request) self.assertEqual( force_text(request.POST.get('csrfmiddlewaretoken')), force_text(csrf_token) )
def test_round_trip_loop_header(self): ''' Checks a wide range of input tokens and keys ''' for _ in range(1000): request = RequestFactory().get('/') csrf_token = get_random_string(32) request.META['CSRF_COOKIE'] = csrf_token token = csrf(request)['csrf_token'] request = RequestFactory().post( '/', HTTP_X_CSRFTOKEN=force_text(token), HTTP_X_REQUESTED_WITH='XMLHttpRequest' ) middleware = CSRFCryptMiddleware() middleware.process_request(request) self.assertEqual( force_text(request.META.get('HTTP_X_CSRFTOKEN')), force_text(csrf_token) )