TL;DR
Replay attacks happen when someone records a valid communication and sends it again later to trick the system. This guide shows simple ways to stop them on lightweight channels, like adding timestamps or unique numbers (nonces) to your messages.
How Replay Attacks Work
Imagine Alice sending Bob a message saying “Open the door”. A replay attack happens if Mallory intercepts this message and sends it again later – even after Alice has already closed the door. Bob would open the door for Mallory without Alice’s permission.
Stopping Replay Attacks
- Timestamps: Add a timestamp to each message.
- The receiver (Bob) checks if the timestamp is recent. If it’s too old, the message is rejected.
- Important: Keep both Alice and Bob’s clocks synchronized! Even small differences can cause problems. Network Time Protocol (NTP) helps with this.
# Example Python timestamp checkimport time messagetime = float(message['timestamp']) currenttime = time.time() time_difference = currenttime - messagetime if time_difference > 30: # Reject messages older than 30 seconds print("Message is too old!") else: process_message(message) - Nonces (Numbers Used Once): Use a unique, random number in each message.
- The receiver keeps track of the last few nonces it saw. If it sees the same nonce again, it knows it’s a replay attack and rejects the message.
- Each message needs a new, unpredictable nonce.
# Example Python nonce checkseen_nonces = set() messagenonce = int(message['nonce']) if messagenonce in seen_nonces: print("Replay attack detected!") else: process_message(message) seen_nonces.add(messagenonce) - Sequence Numbers: Similar to nonces, but numbers increase with each message.
- The receiver expects messages in order. If it receives a message with an out-of-sequence number, it rejects it.
- Requires careful handling of lost or delayed messages – you might need to allow for some gaps.
# Example Python sequence number checklast_seen_sequence = 0 messagesequence = int(message['sequence']) if messagesequence != last_seen_sequence + 1: print("Out of order message!") else: process_message(message) last_seen_sequence = messagesequence - Message Authentication Codes (MACs): Use a secret key to create a MAC for each message.
- The receiver recalculates the MAC using the same key. If the calculated MAC doesn’t match the one in the message, it’s likely been tampered with or replayed.
- This protects against both replay and modification attacks.
MACs are more complex to implement but offer stronger security.
Important Considerations
- Clock Synchronization: For timestamps, accurate clock synchronization is critical.
- Nonce/Sequence Number Storage: The receiver needs enough storage to remember recent nonces or sequence numbers.
- Key Management (for MACs): Securely manage the secret key used for MAC calculations.
cyber security Best Practices
Always combine these techniques with other cyber security measures, like encryption, for a more robust system.

