mirror of
https://github.com/rstrouse/ESPSomfy-RTS.git
synced 2026-10-31 13:52:15 +01:00
feat: sign tokens with a secret key, compare them in constant time
Tokens were HMAC(serverId, credentials + client IP). serverId is public (mDNS, MQTT, /loginContext), so anyone who saw a token could test PIN guesses offline. The key is now 32 random bytes made on first boot in their own NVS namespace, which no settings save clears and no backup holds. It is made before WiFi starts, from the bootloader's entropy source. Tokens are compared with tokenMatches, which takes the same time whatever the guess, on the apikey header, the socket upgrade and /login. createAPIToken never freed its mbedtls context, so every token it made leaked: 563 bytes per login on the device, until it ran out of memory after about 150 logins. It now frees it: 0 bytes over 500 logins. Every token made before the upgrade is refused once. The web UI asks for login again, and Home Assistant 3.0 logs in again by itself. Closes #80 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
ff7517e10f
commit
43191ba312
8 changed files with 144 additions and 13 deletions
26
src/ApiToken.h
Normal file
26
src/ApiToken.h
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
#ifndef apitoken_h
|
||||
#define apitoken_h
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
// A token is HMAC-SHA256(token key, PIN or username:password + ":" + client
|
||||
// IP) in hex. The token key is 32 random bytes the device makes on first boot
|
||||
// and keeps in NVS: it never leaves the device.
|
||||
#define API_TOKEN_KEY_SIZE 32
|
||||
|
||||
// True when given is the expected token. It takes the same time whatever
|
||||
// given holds, so the time doesn't tell how much of a guess was right. Only
|
||||
// expected's length shows, and every token has the same one.
|
||||
inline bool tokenMatches(const char *expected, const char *given) {
|
||||
if(!expected || !given || !expected[0]) return false;
|
||||
uint8_t diff = 0;
|
||||
for(size_t i = 0; expected[i]; i++) {
|
||||
diff |= (uint8_t)(expected[i] ^ *given);
|
||||
// A shorter given compares its terminator with the rest of expected.
|
||||
if(*given) given++;
|
||||
}
|
||||
// A longer given doesn't match either.
|
||||
diff |= (uint8_t)*given;
|
||||
return diff == 0;
|
||||
}
|
||||
#endif
|
||||
Loading…
Add table
Add a link
Reference in a new issue