Requirement #
- public facing API with public client (e.g. mobile app, web app)
- bot intercepted the requests and replaying them
Approaches #
- IP rate limiting (extra cost)
- Enterprise solution (extra cost)
- AWS WAF Bot Control
- Recaptcha
API key(not safe for public client)- nonce (with authentication)
Simple solution without extra cost: Nonce #
The nonce helps to prove that the message received was sent by the intended sender and was not intercepted and resent by a bad actor.
How to choose a nonce #
-
Timestamp
- client use timestamp as nonce in the request
- server should verify the timestamp within a certain range
- beware of client time skew
- user could change the device time, therefore we could use timestamp returned from server.
-
random number
- client generates a random number as nonce
- server checks the nonce is not used before
- cons: need to store nonce in server for some time (e.g. in cache)
Is nonce enough? #
using nonce without encryption or authentication is easy to be guessed by attacker.
Encryption / Authentication #
- either way is fine
- for authentication, HMAC is a good choice
- for encryption, asymmetric encryption is a good choice for public client.
Solution I used #
- client has public key from server
- client receive timestamp from server as nonce
- client encrypt the nonce with public key and send to server
- server decrypt the nonce with private key and verify the timestamp within a certain range.