Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent session hijacking #242

Open
wants to merge 4 commits into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/flask_session/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,10 @@ def __init__(

def _generate_sid(self, session_id_length: int) -> str:
"""Generate a random session id."""
return secrets.token_urlsafe(session_id_length)
new_sid = secrets.token_urlsafe(session_id_length)
if self._retrieve_session_data(new_sid):
raise RuntimeError("Session ID already exists in the database.")
return new_sid

# TODO: Remove in 1.0.0
def _get_signer(self, app: Flask) -> Signer:
Expand Down
11 changes: 7 additions & 4 deletions src/flask_session/dynamodb/dynamodb.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,11 +143,14 @@ def _create_table(self):

def _retrieve_session_data(self, store_id: str) -> Optional[dict]:
# Get the saved session (document) from the database
document = self.store.get_item(Key={"id": store_id}).get("Item")
session_is_not_expired = Decimal(datetime.utcnow().timestamp()) <= document.get(
try:
document = self.store.get_item(Key={"id": store_id}).get("Item")
except self.client.meta.client.exceptions.ResourceNotFoundException:
return None

if document and Decimal(datetime.utcnow().timestamp()) <= document.get(
"expiration"
)
if document and session_is_not_expired:
):
serialized_session_data = want_bytes(document.get("val").value)
return self.serializer.loads(serialized_session_data)
return None
Expand Down
Loading