How to create and use nonces
You have a scoring system that awards points based on game plays, validated via hashing to ensure request integrity. The attack you are facing is straightforward: an adversary captures a valid HTTP request containing a high score and replays it. Because your current validation relies solely on the hash of the request data, the replayed packet passes verification without modification. This is a classic replay attack, and hashing alone does not prevent it if the same data can be submitted multiple times.
To mitigate this, you need to introduce uniqueness into each request so that even if an attacker captures the payload, they cannot reuse it later. Nonces (numbers used once) provide exactly this property. A nonce is a random value generated by your server and included in the client's request. When your backend validates the request, it checks two things: first, does the hash match? Second, has this specific nonce already been processed? If either check fails, the request is rejected.
There are several ways to implement this in PHP, depending on your architecture and state management needs. The simplest approach for a single-server setup involves storing accepted nonces in memory or a cache layer like Redis. When the game client sends a request with a nonce, you generate one if it isn't present, or validate the existing one. Your validation logic must ensure that once a nonce is marked as used, any subsequent attempt to use it returns an error.
Here is a basic pattern using PHP and Redis:
$nonce = $request->input('nonce');
$score = $request->input('score');
// Generate a secure random hex string if one isn't provided or has expired
if (!$nonce || !is_valid_nonce_format($nonce)) {
$nonce = bin2hex(random_bytes(32));
}
// Check if this nonce is already used in Redis
$key = "nonce:{$nonce}";
$is_used = $redis->get($key);
if ($is_used) {
// Replay detected
http_response_code(409); // Conflict
exit('Nonce already used');
}
// Validate the hash of the request data (excluding nonce if necessary)
$expected_hash = hash_hmac('sha256', $request->getContent(), $secret_key);
if ($expected_hash !== $request->header('X-Request-Signature')) {
http_response_code(401);
exit('Invalid signature');
}
// Mark the nonce as used
$redis->set($key, 'used', ['EX' => 3600]); // Optional: set a TTL if you want to allow re-login after an hour
// Proceed with awarding points
$redis->hincrby("user_scores", $userId, $score);
In this example, the nonce is treated as a one-time token. Once Redis records it as used, any duplicate request fails immediately. If you choose not to store nonces in Redis, you can use a database table with a unique constraint on the nonce column. This adds persistence across server restarts but introduces a slight performance cost due to disk I/O.
One critical consideration is how you handle session state versus stateless validation. If your system relies on sessions, you might embed the nonce directly into the session data, ensuring it remains tied to a specific user session lifetime. However, for high-throughput systems like game scoring where latency matters, a cache-backed approach is often preferable.
Another pitfall is relying solely on the timestamp or request ID as a nonce without proper entropy. Use random_bytes() instead of rand() to generate cryptographically secure values. Also, ensure that your hash algorithm includes the secret key (HMAC) rather than just hashing the raw data, preventing attackers from forging signatures themselves.
If you are working within a Laravel application, you can leverage existing helper methods or create a custom service trait to manage nonce generation and validation consistently across your scoring endpoints. The principles remain the same regardless of framework: generate, include in request, validate hash, mark as used, and reject duplicates.
