Skip to content

Commit

Permalink
fix: patch potential timing attack with secrets.compare_digest
Browse files Browse the repository at this point in the history
  • Loading branch information
sambarnes committed Dec 27, 2023
1 parent 09d343e commit a4c2eb1
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion modal/shared/config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
import secrets
from typing import Annotated

from fastapi import Depends, HTTPException, status
Expand All @@ -19,10 +20,15 @@ def auth(self, token: Annotated[HTTPAuthorizationCredentials, Depends(_auth)]) -
Raises: HTTPException(401) if the token is invalid.
"""
if token.credentials != os.environ[self.api_key_id]:

# Timing attacks possible through direct comparison. Prevent it with a constant time comparison here.
got_credential = token.credentials.encode()
want_credential = os.environ[self.api_key_id].encode()
if not secrets.compare_digest(got_credential, want_credential):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect bearer token",
headers={"WWW-Authenticate": "Bearer"},
)

return token

0 comments on commit a4c2eb1

Please sign in to comment.