Insecure session expiration time - Python

Insecure session expiration time - Python

Need

Enforce secure session expiration time

Context

  • Usage of Python 3 for writing and executing Python code
  • Usage of Django for building web applications in Python

Description

Non compliant code

        # settings.py
from django.conf import settings

# Session Cookie Age
# This is the time in seconds that the session cookie will live.
# The default is 2 weeks, which is 1209600 seconds
SESSION_COOKIE_AGE = 1209600
        
        

The above code snippet is taken from the settings.py file in a Django backend application. It defines the SESSION_COOKIE_AGE which is the duration in seconds that the session cookie will live. The default value is 2 weeks, which is 1209600 seconds.

This is where the vulnerability lies. According to the vulnerability context, user sessions should expire after 5 minutes of inactivity. However, in the above code, the session cookie age is set to 2 weeks. This means that even if a user is inactive for more than 5 minutes, their session will not expire, leading to potential security risks.

To fix this vulnerability, the SESSION_COOKIE_AGE should be set to 5 minutes (300 seconds) of inactivity.

This vulnerability is a risk because it allows for the possibility of session hijacking. If a malicious user gets access to a user's session cookie, they can impersonate that user for up to 2 weeks, instead of just 5 minutes.

In addition, the long session expiration time could lead to resource exhaustion on the server if many sessions are left open for long periods of time.

Steps

  • Identify the configuration setting for session expiration in your settings.py file.
  • Change the SESSION_COOKIE_AGE value to 300. This value is in seconds, so 300 seconds equals 5 minutes.
  • Save the changes and restart your application for the changes to take effect.

Compliant code

        # settings.py
from django.conf import settings

# Session Cookie Age
# This is the time in seconds that the session cookie will live.
# We set it to 5 minutes, which is 300 seconds
SESSION_COOKIE_AGE = 300
        
        

In the original code, the session cookie age was set to 1209600 seconds, which is equivalent to 2 weeks. This means that a user's session would remain active for 2 weeks, even if the user is inactive. This is a security vulnerability as it could potentially allow unauthorized users to hijack the session.

To fix this vulnerability, we have changed the SESSION_COOKIE_AGE to 300 seconds, which is equivalent to 5 minutes. This means that if a user is inactive for 5 minutes, their session will expire and they will need to log in again. This reduces the window of opportunity for an unauthorized user to hijack the session.

After making this change, remember to save the settings.py file and restart your application for the changes to take effect.

References