Blog | G5 Cyber Security

Token Expiry: Dealing with Clock Drift

TL;DR

When your system relies on token expiry for authorization but doesn’t have a reliable clock (e.g., distributed systems, mobile apps), use a sliding window approach combined with token refresh mechanisms and consider using monotonic clocks where possible. This prevents issues caused by time differences between servers or devices.

Understanding the Problem

Token expiry is a common security practice. However, if your system’s clocks aren’t perfectly synchronized, tokens can expire prematurely (false negatives) or remain valid longer than intended (security risk). This is especially problematic in:

Relying on Network Time Protocol (NTP) alone isn’t always enough for strict security requirements due to potential drift.

Solution Steps

  1. Sliding Window Approach: Instead of checking if a token is expired based on a fixed time, allow a small grace period.
  • Token Refresh Mechanisms: Don’t rely solely on long-lived tokens. Implement a refresh token system.
  • Monotonic Clocks (Where Possible): Use a monotonic clock if your programming language and environment support it.
  • Centralized Token Validation: If feasible, validate tokens against a central authority that has a reliable clock.
  • Token Storage with Expiry Time: Store token expiry timestamps when issuing them.
  • Consider Clock Drift Detection: Implement mechanisms to detect significant clock drift.
  • Code Example (Simplified Token Validation)

    This is a very basic example in Python, demonstrating the sliding window concept.

    import time
    
    def validate_token(token, expiry_timestamp, grace_period=300): # Grace period in seconds
      current_time = int(time.time())
      if current_time <= expiry_timestamp + grace_period:
        return True
      else:
        return False
    
    # Example Usage
    token_expiry = int(time.time()) + 3600 # Token expires in 1 hour
    if validate_token("my_token", token_expiry):
      print("Token is valid")
    else:
      print("Token has expired")

    Important Considerations

    Exit mobile version