CSRF attacks and token protection in PHP - Time & Space Complexity
We want to understand how the time it takes to check CSRF tokens grows as the number of requests or tokens increases.
How does the token verification process scale when handling many requests?
Analyze the time complexity of the following PHP code snippet for CSRF token verification.
// Assume session token is stored
session_start();
function verifyCsrfToken($token) {
if (!isset($_SESSION['csrf_token'])) {
return false;
}
return hash_equals($_SESSION['csrf_token'], $token);
}
$userToken = $_POST['csrf_token'] ?? '';
if (verifyCsrfToken($userToken)) {
// Proceed with request
} else {
// Reject request
}
This code checks if the CSRF token sent by the user matches the one stored in the session.
Look for operations that repeat or take time depending on input size.
- Primary operation: Comparing two fixed-length strings with
hash_equals. - How many times: Once per request, no loops or recursion involved.
The token comparison always takes about the same time because tokens have fixed length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 requests | 10 token comparisons |
| 100 requests | 100 token comparisons |
| 1000 requests | 1000 token comparisons |
Pattern observation: The time grows linearly with the number of requests, but each check is very fast and constant time.
Time Complexity: O(1)
This means each token check takes the same small amount of time, no matter what.
[X] Wrong: "Checking CSRF tokens gets slower as more users use the site."
[OK] Correct: Each token check is independent and constant time, so more users do not slow down a single check.
Understanding how security checks like CSRF token verification scale helps you write safe and efficient web applications.
What if the token was stored in a database and you had to search for it each time? How would the time complexity change?
Practice
Solution
Step 1: Understand CSRF attack basics
CSRF attacks trick a user into submitting unwanted actions on a trusted site.Step 2: Role of CSRF token
A CSRF token is a unique value that verifies the request is from the legitimate user, preventing unauthorized commands.Final Answer:
To prevent unauthorized commands from being transmitted from a user the website trusts -> Option BQuick Check:
CSRF token purpose = prevent unauthorized commands [OK]
- Confusing CSRF tokens with password encryption
- Thinking CSRF tokens speed up websites
- Believing CSRF tokens validate input format
Solution
Step 1: Identify secure token generation
CSRF tokens must be random and hard to guess, so secure random functions are used.Step 2: Choose the correct function
random_bytes() generates cryptographically secure random bytes, suitable for tokens.Final Answer:
random_bytes() -> Option AQuick Check:
Secure token generation = random_bytes() [OK]
- Using md5() which is not secure for tokens
- Confusing htmlspecialchars() with token generation
- Using strtoupper() which only changes case
$_SESSION['csrf_token'] = 'abc123';
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
echo 'Valid request';
} else {
echo 'Invalid request';
}Solution
Step 1: Check token comparison logic
The code compares the POST token with the session token for equality.Step 2: When tokens match
If tokens match, it echoes 'Valid request'. If not, 'Invalid request'.Final Answer:
Valid request -> Option CQuick Check:
Matching tokens = Valid request [OK]
- Assuming error if POST token is set correctly
- Ignoring isset() check causing errors
- Thinking output is empty when tokens match
session_start();
if ($_POST['csrf_token'] == $_SESSION['csrf_token']) {
echo 'Token valid';
} else {
echo 'Token invalid';
}Solution
Step 1: Analyze token existence check
The code compares $_POST['csrf_token'] without verifying if it exists, risking undefined index error.Step 2: Importance of isset()
Using isset() prevents errors by ensuring the token is present before comparison.Final Answer:
Missing check if $_POST['csrf_token'] is set before comparing -> Option DQuick Check:
Check token existence before compare = Missing isset() [OK]
- Ignoring isset() causing runtime errors
- Thinking == vs === affects token validation here
- Calling session_start() after token check
Solution
Step 1: Token generation and storage
Token must be generated before showing the form and stored in session to verify later.Step 2: Embedding and validation
Embed the token in a hidden form field and check it against the session token on submission.Final Answer:
Generate token on form display, store in session, embed in hidden input, then check token on form submission. -> Option AQuick Check:
Token lifecycle = generate, store, embed, validate [OK]
- Generating token after form submission
- Not storing token in session
- Using static tokens without session storage
Ready to prove it?
Pass the test and this pattern moves unknown
