duck.http.middlewares.security.csrf

Module containing CSRFMiddleware class which mitigates against Cross-Site-Request-Forgery (CSRF) attacks.

Module Contents

Classes

CSRFMiddleware

Middleware for mitigating Cross-Site Request Forgery (CSRF) attacks.

Functions

add_new_csrf_cookie

Generates a new CSRF secret and saves it in the request’s metadata.

generate_csrf_secret

Returns a secure random CSRF secret containing only letters and digits.

generate_dynamic_secret_key

Dynamically generates a secure, consistent key based on system-specific data.

get_csrf_token

Generates a new CSRF token and saves the CSRF secret in the request.META.

mask_cipher_secret

Masks CSRF secret to produce a secure CSRF token.

unmask_cipher_token

Unmasks a CSRF token to retrieve the original CSRF secret.

Data

ALLOWED_CHARACTERS

CSRF_SECRET_LENGTH

CSRF_SESSION_KEY

CSRF_TOKEN_LENGTH

CSRF_USE_SESSIONS

API

duck.http.middlewares.security.csrf.ALLOWED_CHARACTERS

None

exception duck.http.middlewares.security.csrf.CSRFCookieError

Bases: Exception

Exception class for CSRF cookie errors.

Initialization

Initialize self. See help(type(self)) for accurate signature.

class duck.http.middlewares.security.csrf.CSRFMiddleware

Bases: duck.http.middlewares.BaseMiddleware

Middleware for mitigating Cross-Site Request Forgery (CSRF) attacks.

This middleware verifies the authenticity of requests by comparing the CSRF token included in the request body (for methods such as POST, PUT, etc.) with the one securely stored in the user’s session (request.SESSION). This helps protect against unauthorized actions being performed using an authenticated user’s session.

The middleware operates with the following behavior:

  • Conditional Activation: When USE_DJANGO=True, this middleware is skipped unless the request path corresponds to a Duck explicit URL. Duck explicit URLs are listed in DUCK_EXPLICIT_URLS and should not be proxied to Django at any point.

  • Prevention of CSRF Attacks: CSRF attacks exploit a user’s authenticated session to perform unauthorized actions on their behalf. By ensuring the CSRF token in the request body matches the one stored in the Session or Cookie, this middleware mitigates the risk of such attacks.

Variables:
  • USE_DJANGO – Flag indicating whether to use Django for handling requests.

  • DUCK_EXPLICIT_URLS – List of URLs that should be handled by Duck and not proxied to Django.

Methods:

  • process_request(request): Verifies the CSRF token in the request and compares it with the Csrf Cookie/Secret to ensure authenticity.

classmethod _check_origin_ok(request)

Checks if request Origin is good origin

Returns:

True if request origin is ok

Raises:

OriginError – If origin provided is invalid in any way

classmethod _check_referer_ok(request)

Checks if request Referer is good referer

Returns:

True if request referer is ok

Raises:

RefererError – If referer provided is invalid in any way

Checks for the csrf cookie sent in request.

Raises:

CSRFCookieError – This is raised if there is any issue with the CSRF cookie sent by the client.

debug_message: str

‘CSRFMiddleware: CSRF token missing or invalid’

classmethod get_error_response(request)
classmethod process_request(request: duck.http.request.HttpRequest)
classmethod process_response(response, request)
classmethod rotate_csrf_token()

Resets the request csrf secret and returns the rotated csrf secret.

duck.http.middlewares.security.csrf.CSRF_SECRET_LENGTH

None

duck.http.middlewares.security.csrf.CSRF_SESSION_KEY

None

duck.http.middlewares.security.csrf.CSRF_TOKEN_LENGTH

None

duck.http.middlewares.security.csrf.CSRF_USE_SESSIONS

None

exception duck.http.middlewares.security.csrf.OriginError

Bases: Exception

Exception class for invalid HTTP Origin

Initialization

Initialize self. See help(type(self)) for accurate signature.

exception duck.http.middlewares.security.csrf.RefererError

Bases: Exception

Exception class for invalid HTTP Referer

Initialization

Initialize self. See help(type(self)) for accurate signature.

Generates a new CSRF secret and saves it in the request’s metadata.

Parameters:
  • request – The HTTP request object.

  • secret_key – The dynamic secret key used for signing the CSRF token.

duck.http.middlewares.security.csrf.generate_csrf_secret() str

Returns a secure random CSRF secret containing only letters and digits.

duck.http.middlewares.security.csrf.generate_dynamic_secret_key() bytes

Dynamically generates a secure, consistent key based on system-specific data.

Returns:

A dynamic, secure key derived from system-specific data.

Return type:

bytes

duck.http.middlewares.security.csrf.get_csrf_token(request)

Generates a new CSRF token and saves the CSRF secret in the request.META.

Parameters:

request – The http request.

This function performs the following actions:

  1. Generates a new CSRF token (Csrf_Token), a scrambled/random token to be sent to the user.

  2. Saves the CSRF secret (Csrf_Secret) in:

    • request.META under the key ‘CSRF_COOKIE’

The CSRF token (Csrf_Token) is sent to the client each time this function is called. (This is done by CSRFMiddleware)

duck.http.middlewares.security.csrf.mask_cipher_secret(secret: str) str

Masks CSRF secret to produce a secure CSRF token.

Parameters:

secret – The CSRF secret.

Returns:

The CSRF token.

Return type:

str

Raises:

ValueError – If the secret contains invalid characters.

duck.http.middlewares.security.csrf.unmask_cipher_token(token: str) str

Unmasks a CSRF token to retrieve the original CSRF secret.

Parameters:

token – The CSRF token.

Returns:

The original CSRF secret.

Return type:

str

Raises:

ValueError – If the token is invalid or tampered with.