Opened 9 years ago

Closed 9 years ago

Last modified 9 years ago

#25017 closed Cleanup/optimization (fixed)

settings.DISALLOWED_USER_AGENTS should raise PermissionDenied

Reported by: François Schiettecatte Owned by: Sujay S Kumar
Component: Core (Other) Version: 1.8
Severity: Normal Keywords: DISALLOWED_USER_AGENTS, PermissionDenied
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: yes
Easy pickings: no UI/UX: no

Description

The check against settings.DISALLOWED_USER_AGENTS should throw a PermissionDenied exception as opposed to returning an HttpResponseForbidden() so that handler403 is invoked.

Code touched would be:

https://github.com/django/django/blob/master/django/middleware/common.py#L10

from django.core.exceptions import PermissionDenied

https://github.com/django/django/blob/master/django/middleware/common.py#L47-56

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']):
            logger.warning('Forbidden (User agent): %s', request.path,
                extra={
                    'status_code': 403,
                    'request': request
                }
            )
            raise PermissionDenied

https://github.com/django/django/blob/master/tests/middleware/tests.py#L254-261

@override_settings(DISALLOWED_USER_AGENTS=[re.compile(r'foo')])
def test_disallowed_user_agents(self):
    with patch_logger('django.request', 'warning') as log_messages:
        request = self.rf.get('/slash')
        request.META['HTTP_USER_AGENT'] = 'foo'
        with self.assertRaises(self, PermissionDenied):
            CommonMiddleware().process_request(request)
            self.assertEqual(log_messages, ['Forbidden (User agent): /slash'])

Change History (8)

comment:1 by Tim Graham, 9 years ago

Could you submit a pull request?

comment:2 by Sujay S Kumar, 9 years ago

Owner: changed from nobody to Sujay S Kumar
Status: newassigned

comment:3 by Sujay S Kumar, 9 years ago

Has patch: set
Needs tests: set

comment:4 by Moritz Sichert, 9 years ago

SujaySKumar's pull request: https://github.com/django/django/pull/4915

comment:5 by Tim Graham, 9 years ago

Needs tests: unset
Summary: settings.DISALLOWED_USER_AGENTS should throw PermissionDenied exceptionsettings.DISALLOWED_USER_AGENTS should raise PermissionDenied
Triage Stage: UnreviewedAccepted

comment:6 by Tim Graham, 9 years ago

Patch needs improvement: set

comment:7 by Tim Graham <timograham@…>, 9 years ago

Resolution: fixed
Status: assignedclosed

In 2e70bf3:

Fixed #25017 -- Allowed customizing the DISALLOWED_USER_AGENTS response

comment:8 by Tim Graham <timograham@…>, 9 years ago

In 6c592e79:

Removed unused code after refs #25017.

Note: See TracTickets for help on using tickets.
Back to Top