Excessive 404 Middleware

class smarter.lib.django.middleware.excessive_404.SmarterBlockExcessive404Middleware(get_response, *args, **kwargs)[source]

Bases: SmarterMiddlewareMixin

Middleware that throttles unauthenticated clients producing excessive 404s.

This mitigates:

  • automated scanners

  • brute-force URL probing

  • broken crawlers

  • vulnerability enumeration attempts

async async_process_response(request, response)[source]

Async entry point for ASGI deployments: count anonymous 404s per client ip, and block excessive ones.

Unlike process_response(), it does not check the ENABLE_MIDDLEWARE_EXCESSIVE_404 switch.

Parameters:
Return type:

HttpResponseBase

Returns:

The response, or a 403 response when the client has exceeded the throttle limit.

property formatted_class_name: str[source]

Return the formatted class name for logging.

It names the instance, not a request.

classmethod get_throttle_key(client_ip)[source]

Return the cache key of a client’s 404 counter.

Parameters:

client_ip (str) – The client’s ip address.

Return type:

str

Returns:

The cache key.

increment_throttle(throttle_key)[source]

Add one to a client’s 404 counter in the cache, and reset its THROTTLE_TIMEOUT.

While the cache can’t be written, e.g. during a Redis outage, the 404 isn’t counted.

Parameters:

throttle_key (str) – The cache key of the client’s counter, from get_throttle_key().

Return type:

None

is_ignored_path(path)[source]

Determine whether 404s on this path should never count toward the throttle.

Parameters:

path (str) – The request path.

Return type:

bool

Returns:

True for amnesty urls and JSON schema lookups.

log_404_event(request, client_ip, blocked_count)[source]

Log a 404 probe at DEBUG, sampled every LOG_SAMPLE_RATE counts to reduce spam during bot scans.

Parameters:
  • request (HttpRequest) – The request.

  • client_ip (str) – The client’s ip address.

  • blocked_count (int) – The client’s 404 count before this one.

Return type:

None

process_response(request, response)[source]

Sync entry point: count anonymous 404s per client ip, and block excessive ones.

It does nothing unless the ENABLE_MIDDLEWARE_EXCESSIVE_404 waffle switch is active.

Parameters:
Return type:

HttpResponseBase

Returns:

The response, or a 403 response when the client has exceeded the throttle limit.