Sensitive Files Middleware

class smarter.lib.django.middleware.sensitive_files.SmarterBlockSensitiveFilesMiddleware(get_response)[source]

Bases: SmarterMiddlewareMixin

Middleware that blocks requests probing for sensitive files.

Features:

  • ASGI and WSGI compatible

  • Path normalization

  • Amnesty support

  • Request throttling

  • In-memory inspection

__init__(get_response)[source]

Note: this needs to exist; something in the Python MRO requires it, even if it does nothing.

If you remove this, you will get a mysterious error about something downstream expecting exactly one object.

property formatted_class_name: str[source]

Return the formatted class name for logging.

It names the instance, not a request.

static get_throttle_key(client_ip)[source]

Return the cache key of a client’s probe count.

Parameters:

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

Return type:

str

Returns:

The cache key.

increment_throttle(client_ip)[source]

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

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

Parameters:

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

Return type:

None

is_amnesty_path(path)[source]

Return whether a path is exempt from the sensitive-file check.

A path is exempt when it is an amnesty url, or when it or one of its segments matches an allowed pattern.

Parameters:

path (str) – The normalized request path.

Return type:

bool

Returns:

True if the path is exempt.

classmethod is_sensitive_request(path)[source]

Return whether a normalized path asks for a sensitive file.

Parameters:

path (str) – The normalized request path.

Return type:

bool

Returns:

True if the path, or one of its segments, is a sensitive file.

is_throttled(client_ip)[source]

Return whether a client has reached the throttle limit of sensitive-file probes.

While the cache can’t be read, e.g. during a Redis outage, no client is throttled (issue #1091).

Parameters:

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

Return type:

bool

Returns:

True if the client’s count, in the cache, is at least THROTTLE_LIMIT.

static iter_path_segments(path)[source]

Return the non-empty segments of a path, e.g. a and b for /a//b/.

Parameters:

path (str) – The path.

Return type:

Iterable[str]

Returns:

A generator of the segments.

static normalize_path(path)[source]

Normalize a request path, to defeat traversal and encoding bypasses.

The path is url-decoded twice, NFKC-normalized, its backslashes turned into slashes, its null bytes removed, its repeated slashes collapsed, its traversal resolved, and lower-cased.

Parameters:

path (str) – The raw request path.

Return type:

str

Returns:

The normalized path, which always starts with /.