Files
led-controller/main/auth.c
T
jimmyandClaude Haiku 5.5 f0615dc1b7 feat: users, roles and per-area permissions, production demo image
The controller checks every route against the signed-in user's role, with
levels none, view, control and edit per area. Guests get the permissions
of a built-in guest role. Auth stays off until the first user exists;
LED_ADMIN_USER and LED_ADMIN_PASSWORD create the first admin.

Sessions are cookies, passwords are PBKDF2-SHA256, and logins lock per
username after five failures. The simulator's WebSocket checks the view
permission at handshake and per frame; /ws needs devices control. The web
UI gets a sign-in button, a sign-in prompt on refused changes, and a users
and roles screen.

Also: the device build gets the bridge include path and forward type it
was missing, Dockerfile.sim runs non-root, and Dockerfile.prod with
docker-compose.prod.yml runs the controller on an internal network behind
Caddy for HTTPS.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-17 00:29:04 +13:00

1302 lines
40 KiB
C

#include "auth.h"
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "esp_log.h"
#include "esp_random.h"
#include "esp_timer.h"
#include "store.h"
static const char *TAG = "auth";
#define AREA_N 10
static const char *const AREAS[AREA_N] = {
"presets", "sequences", "zones", "groups", "devices", "outputs", "patterns", "sim", "settings", "users",
};
// Control actions (POST) on these areas need control, not edit
static const char *const CONTROL_WORDS[] = {
"play", "stop", "fire", "overlay", "sync-phase", "set-current", "current", "apply", "send", "push",
"brightness", "identify", "ping", "resolve-brightness", "test",
};
#define COOKIE "led_session"
#define TOKEN_LEN 64
#define PBKDF2_ITER 10000
#define SESS_MAX 32
#define SESS_TTL_US (30LL * 24 * 3600 * 1000000)
#define WS_MAX 16
/* ------------------------------------------------------------------ sha-256, hmac, pbkdf2
* Pure C, so the same hashes come out on every build (the linux host builds have no mbedtls). */
typedef struct {
uint32_t h[8];
uint8_t buf[64];
size_t bl;
uint64_t total;
} sha_t;
static const uint32_t K256[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
};
static uint32_t rotr(uint32_t x, int n)
{
return (x >> n) | (x << (32 - n));
}
static void sha_init(sha_t *c)
{
static const uint32_t H0[8] = {
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
};
memcpy(c->h, H0, sizeof(H0));
c->bl = 0;
c->total = 0;
}
static void sha_block(uint32_t h[8], const uint8_t b[64])
{
uint32_t w[64];
for (int i = 0; i < 16; i++) {
w[i] = ((uint32_t)b[4 * i] << 24) | ((uint32_t)b[4 * i + 1] << 16) | ((uint32_t)b[4 * i + 2] << 8) | b[4 * i + 3];
}
for (int i = 16; i < 64; i++) {
uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
}
uint32_t a = h[0], bb = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7];
for (int i = 0; i < 64; i++) {
uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
uint32_t ch = (e & f) ^ (~e & g);
uint32_t t1 = hh + S1 + ch + K256[i] + w[i];
uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
uint32_t maj = (a & bb) ^ (a & c) ^ (bb & c);
uint32_t t2 = S0 + maj;
hh = g;
g = f;
f = e;
e = d + t1;
d = c;
c = bb;
bb = a;
a = t1 + t2;
}
h[0] += a;
h[1] += bb;
h[2] += c;
h[3] += d;
h[4] += e;
h[5] += f;
h[6] += g;
h[7] += hh;
}
static void sha_update(sha_t *c, const void *p, size_t n)
{
const uint8_t *d = p;
c->total += n;
while (n) {
size_t take = 64 - c->bl;
if (take > n) {
take = n;
}
memcpy(c->buf + c->bl, d, take);
c->bl += take;
d += take;
n -= take;
if (c->bl == 64) {
sha_block(c->h, c->buf);
c->bl = 0;
}
}
}
static void sha_final(sha_t *c, uint8_t out[32])
{
uint64_t bits = c->total * 8;
uint8_t one = 0x80, zero = 0;
sha_update(c, &one, 1);
while (c->bl != 56) {
sha_update(c, &zero, 1);
}
uint8_t len[8];
for (int i = 0; i < 8; i++) {
len[i] = (uint8_t)(bits >> (56 - 8 * i));
}
sha_update(c, len, 8);
for (int i = 0; i < 8; i++) {
out[4 * i] = (uint8_t)(c->h[i] >> 24);
out[4 * i + 1] = (uint8_t)(c->h[i] >> 16);
out[4 * i + 2] = (uint8_t)(c->h[i] >> 8);
out[4 * i + 3] = (uint8_t)c->h[i];
}
}
// HMAC-SHA256 of m1 || m2 (m2 may be empty)
static void hmac256(const uint8_t *key, size_t kl, const uint8_t *m1, size_t l1, const uint8_t *m2, size_t l2, uint8_t out[32])
{
uint8_t k[64] = { 0 };
if (kl > 64) {
sha_t c;
sha_init(&c);
sha_update(&c, key, kl);
sha_final(&c, k);
} else {
memcpy(k, key, kl);
}
uint8_t ipad[64], opad[64], inner[32];
for (int i = 0; i < 64; i++) {
ipad[i] = k[i] ^ 0x36;
opad[i] = k[i] ^ 0x5c;
}
sha_t c;
sha_init(&c);
sha_update(&c, ipad, 64);
sha_update(&c, m1, l1);
if (l2) {
sha_update(&c, m2, l2);
}
sha_final(&c, inner);
sha_init(&c);
sha_update(&c, opad, 64);
sha_update(&c, inner, 32);
sha_final(&c, out);
}
// PBKDF2-HMAC-SHA256, one 32-byte block
static void pbkdf2(const char *pw, const uint8_t *salt, size_t sl, uint32_t iter, uint8_t out[32])
{
static const uint8_t one[4] = { 0, 0, 0, 1 };
uint8_t u[32], t[32];
hmac256((const uint8_t *)pw, strlen(pw), salt, sl, one, 4, u);
memcpy(t, u, 32);
for (uint32_t i = 1; i < iter; i++) {
hmac256((const uint8_t *)pw, strlen(pw), u, 32, NULL, 0, u);
for (int j = 0; j < 32; j++) {
t[j] ^= u[j];
}
}
memcpy(out, t, 32);
}
static void to_hex(const uint8_t *b, size_t n, char *out)
{
static const char D[] = "0123456789abcdef";
for (size_t i = 0; i < n; i++) {
out[2 * i] = D[b[i] >> 4];
out[2 * i + 1] = D[b[i] & 15];
}
out[2 * n] = 0;
}
static int hexval(char c)
{
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
}
if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
return -1;
}
static bool from_hex(const char *s, uint8_t *out, size_t n)
{
if (!s || strlen(s) != 2 * n) {
return false;
}
for (size_t i = 0; i < n; i++) {
int hi = hexval(s[2 * i]), lo = hexval(s[2 * i + 1]);
if (hi < 0 || lo < 0) {
return false;
}
out[i] = (uint8_t)(hi << 4 | lo);
}
return true;
}
static bool const_eq(const uint8_t *a, const uint8_t *b, size_t n)
{
uint8_t d = 0;
for (size_t i = 0; i < n; i++) {
d |= a[i] ^ b[i];
}
return d == 0;
}
/* ------------------------------------------------------------------ records */
static const char *str_of(const cJSON *o, const char *key)
{
const cJSON *v = cJSON_GetObjectItem(o, key);
return cJSON_IsString(v) ? v->valuestring : NULL;
}
// Sets a key whether or not it exists yet (cJSON_ReplaceItemInObject does nothing for a new key)
static void obj_set(cJSON *o, const char *k, cJSON *v)
{
if (cJSON_GetObjectItem(o, k)) {
cJSON_ReplaceItemInObject(o, k, v);
} else {
cJSON_AddItemToObject(o, k, v);
}
}
static bool valid_name(const char *s)
{
size_t n = s ? strlen(s) : 0;
if (n == 0 || n > 32) {
return false;
}
for (size_t i = 0; i < n; i++) {
if (!isalnum((unsigned char)s[i]) && !strchr("_.-", s[i])) {
return false;
}
}
return true;
}
static int area_index(const char *a)
{
for (int i = 0; i < AREA_N; i++) {
if (strcmp(AREAS[i], a) == 0) {
return i;
}
}
return -1;
}
static int perm_in(const cJSON *role, const char *area)
{
const cJSON *v = cJSON_GetObjectItem(cJSON_GetObjectItem(role, "perms"), area);
if (!cJSON_IsNumber(v)) {
return AUTH_NONE;
}
return v->valueint < 0 ? AUTH_NONE : v->valueint > 3 ? AUTH_EDIT : v->valueint;
}
static int role_perm(const char *role, const char *area)
{
if (!role || !role[0]) {
return AUTH_NONE;
}
const cJSON *r = cJSON_GetObjectItem(store_coll("role"), role);
return r ? perm_in(r, area) : AUTH_NONE;
}
static bool all_edit(const cJSON *perms)
{
for (int i = 0; i < AREA_N; i++) {
const cJSON *v = cJSON_GetObjectItem(perms, AREAS[i]);
if (!cJSON_IsNumber(v) || v->valueint != AUTH_EDIT) {
return false;
}
}
return true;
}
// A perms object from JSON: every area present, unknown areas and bad levels refused
static cJSON *perms_from_json(const cJSON *p, const char **err)
{
if (!cJSON_IsObject(p)) {
*err = "perms must be an object of area: level";
return NULL;
}
cJSON *out = cJSON_CreateObject();
for (int i = 0; i < AREA_N; i++) {
cJSON_AddNumberToObject(out, AREAS[i], AUTH_NONE);
}
const cJSON *it = NULL;
cJSON_ArrayForEach(it, p)
{
if (area_index(it->string) < 0) {
*err = "unknown area in perms";
cJSON_Delete(out);
return NULL;
}
if (!cJSON_IsNumber(it) || it->valueint < 0 || it->valueint > 3) {
*err = "each level must be 0 (none), 1 (view), 2 (control) or 3 (edit)";
cJSON_Delete(out);
return NULL;
}
obj_set(out, it->string, cJSON_CreateNumber(it->valueint));
}
return out;
}
// Users who can change users and roles, counting one user as the role named set_role at set_level
static int managers_after(const char *skip_user, const char *set_role, int set_level)
{
int n = 0;
const cJSON *u = NULL;
cJSON_ArrayForEach(u, store_coll("user"))
{
if (skip_user && strcmp(u->string, skip_user) == 0) {
continue;
}
const char *r = str_of(u, "role");
int level = (set_role && r && strcmp(r, set_role) == 0) ? set_level : role_perm(r, "users");
if (level >= AUTH_EDIT) {
n++;
}
}
return n;
}
static bool auth_enabled_locked(void)
{
return cJSON_GetArraySize(store_coll("user")) > 0;
}
/* ------------------------------------------------------------------ sessions */
typedef struct {
bool used;
char tok[TOKEN_LEN + 1];
char user[33];
int64_t exp;
} sess_t;
static sess_t s_sess[SESS_MAX];
// Failed logins per username: after 5 in a row that name waits 30 s, doubling to 5 min. Other names are unaffected.
#define LOCK_SLOTS 16
typedef struct {
bool used;
char user[33];
int fails;
int64_t until;
} lock_t;
static lock_t s_lock[LOCK_SLOTS];
static lock_t *lock_slot(const char *user, bool create)
{
lock_t *free_slot = NULL, *oldest = &s_lock[0];
for (int i = 0; i < LOCK_SLOTS; i++) {
lock_t *l = &s_lock[i];
if (l->used && strcmp(l->user, user) == 0) {
return l;
}
if (!l->used && !free_slot) {
free_slot = l;
}
if (l->until < oldest->until) {
oldest = l;
}
}
if (!create) {
return NULL;
}
lock_t *slot = free_slot ? free_slot : oldest; // a full table gives up the entry that expires first
memset(slot, 0, sizeof(*slot));
slot->used = true;
snprintf(slot->user, sizeof(slot->user), "%s", user);
return slot;
}
static sess_t *sess_find(const char *tok)
{
int64_t now = esp_timer_get_time();
for (int i = 0; i < SESS_MAX; i++) {
sess_t *s = &s_sess[i];
if (!s->used) {
continue;
}
if (s->exp < now) {
s->used = false;
continue;
}
if (strcmp(s->tok, tok) == 0) {
s->exp = now + SESS_TTL_US;
return s;
}
}
return NULL;
}
static void sess_drop_user(const char *user)
{
for (int i = 0; i < SESS_MAX; i++) {
if (s_sess[i].used && strcmp(s_sess[i].user, user) == 0) {
s_sess[i].used = false;
}
}
}
static void sess_drop_tok(const char *tok)
{
for (int i = 0; i < SESS_MAX; i++) {
if (s_sess[i].used && strcmp(s_sess[i].tok, tok) == 0) {
s_sess[i].used = false;
}
}
}
// A new session for user; the token is written to tok
static void sess_new(const char *user, char tok[TOKEN_LEN + 1])
{
uint8_t r[TOKEN_LEN / 2];
esp_fill_random(r, sizeof(r));
to_hex(r, sizeof(r), tok);
int64_t now = esp_timer_get_time();
int slot = -1, oldest = 0;
for (int i = 0; i < SESS_MAX; i++) {
if (!s_sess[i].used || s_sess[i].exp < now) {
slot = i;
break;
}
if (s_sess[i].exp < s_sess[oldest].exp) {
oldest = i;
}
}
if (slot < 0) {
slot = oldest; // full: the session nearest its expiry gives way
}
sess_t *s = &s_sess[slot];
s->used = true;
snprintf(s->tok, sizeof(s->tok), "%s", tok);
snprintf(s->user, sizeof(s->user), "%s", user);
s->exp = now + SESS_TTL_US;
}
static bool cookie_tok(httpd_req_t *req, char tok[TOKEN_LEN + 1])
{
size_t n = TOKEN_LEN + 1;
tok[0] = 0;
return httpd_req_get_cookie_val(req, COOKIE, tok, &n) == ESP_OK && strlen(tok) == TOKEN_LEN;
}
// The signed-in user and role for this request; false when signed out
static bool session_of(httpd_req_t *req, char *user, size_t un, char *role, size_t rn)
{
char tok[TOKEN_LEN + 1];
if (!cookie_tok(req, tok)) {
return false;
}
store_lock();
bool ok = false;
sess_t *s = sess_find(tok);
if (s) {
const cJSON *u = cJSON_GetObjectItem(store_coll("user"), s->user);
if (u) {
snprintf(user, un, "%s", s->user);
snprintf(role, rn, "%s", str_of(u, "role") ? str_of(u, "role") : "");
ok = true;
}
}
store_unlock();
return ok;
}
/* ------------------------------------------------------------------ classification */
// The request's role: its session's role, or guest when signed out (signed_in says which)
static bool who(httpd_req_t *req, char *user, size_t un, char *role, size_t rn)
{
bool signed_in = session_of(req, user, un, role, rn);
if (!signed_in) {
user[0] = 0;
snprintf(role, rn, "%s", "guest");
}
return signed_in;
}
static auth_need_t need(const char *area, auth_level_t level, bool pub)
{
auth_need_t n = { area, level, pub };
return n;
}
auth_need_t auth_classify(const char *uri, int method)
{
char buf[160];
const char *s[6] = { 0 };
size_t len = strcspn(uri, "?");
if (len >= sizeof(buf)) {
return need("settings", AUTH_EDIT, false); // too long to read: refuse
}
memcpy(buf, uri, len);
buf[len] = 0;
int n = 0;
if (buf[0] == '/') {
char *p = buf + 1;
while (*p && n < 6) {
s[n++] = p;
char *slash = strchr(p, '/');
if (!slash) {
break;
}
*slash = 0;
p = slash + 1;
}
}
const bool get = method == HTTP_GET, post = method == HTTP_POST, put = method == HTTP_PUT;
const char *s0 = n > 0 ? s[0] : "";
const char *s1 = n > 1 ? s[1] : "";
const char *s2 = n > 2 ? s[2] : "";
if (n == 0) {
return get ? need("", AUTH_NONE, true) : need("settings", AUTH_EDIT, false);
}
if (get && (!strcmp(s0, "audio") || !strcmp(s0, "favicon.ico") || !strcmp(s0, "status") || !strcmp(s0, "static"))) {
return need("", AUTH_NONE, true);
}
// The rig page's files are public (its data is not); its websocket checks its own handshake
if (!strcmp(s0, "ws") || (!strcmp(s0, "sim") && n > 1 && !strcmp(s1, "ws"))) {
return need("", AUTH_NONE, true);
}
if (!strcmp(s0, "sim") && get && (n < 2 || (strcmp(s1, "api") && strcmp(s1, "ws")))) {
return need("", AUTH_NONE, true);
}
if (!strcmp(s0, "auth")) {
if (n == 1 && get) {
return need("", AUTH_NONE, true);
}
if (n == 2 && post && (!strcmp(s1, "login") || !strcmp(s1, "logout"))) {
return need("", AUTH_NONE, true);
}
if (n == 2 && put && !strcmp(s1, "password")) {
return need("@user", AUTH_NONE, false);
}
return need("users", AUTH_EDIT, false);
}
const char *area = NULL;
bool ctrl_ok = false;
if (!strcmp(s0, "presets")) {
area = "presets";
ctrl_ok = true;
} else if (!strcmp(s0, "sequences")) {
area = "sequences";
ctrl_ok = true;
} else if (!strcmp(s0, "zones") || !strcmp(s0, "profiles") || !strcmp(s0, "scenes")) {
area = "zones";
ctrl_ok = true;
} else if (!strcmp(s0, "groups")) {
area = "groups";
ctrl_ok = true;
} else if (!strcmp(s0, "devices")) {
area = "devices";
ctrl_ok = true;
} else if (!strcmp(s0, "outputs")) {
area = "outputs";
ctrl_ok = true;
} else if (!strcmp(s0, "patterns") || !strcmp(s0, "palettes")) {
area = "patterns";
} else if (!strcmp(s0, "sim")) {
area = "sim";
} else if (!strcmp(s0, "settings") || !strcmp(s0, "ota") || !strcmp(s0, "reboot") || !strcmp(s0, "test")) {
area = "settings";
} else if (!strcmp(s0, "api") && n > 1 && !strcmp(s1, "audio")) {
area = "settings";
} else if (!strcmp(s0, "db")) {
return need("settings", AUTH_EDIT, false); // exports hold everything, so even reads need edit
} else {
return need("settings", AUTH_EDIT, false); // unknown routes fail closed
}
if (!strcmp(s0, "sim") && post && n == 3 && !strcmp(s1, "api") && !strcmp(s2, "room")) {
return need("sim", AUTH_CONTROL, false); // switching the rig's room
}
if (get) {
return need(area, AUTH_VIEW, false);
}
if (post && ctrl_ok) {
for (int i = 1; i < n; i++) {
for (size_t k = 0; k < sizeof(CONTROL_WORDS) / sizeof(CONTROL_WORDS[0]); k++) {
if (!strcmp(s[i], CONTROL_WORDS[k])) {
return need(area, AUTH_CONTROL, false);
}
}
}
}
return need(area, AUTH_EDIT, false);
}
/* ------------------------------------------------------------------ responses */
static esp_err_t send_json(httpd_req_t *req, const char *status, cJSON *o)
{
char *s = cJSON_PrintUnformatted(o);
cJSON_Delete(o);
httpd_resp_set_status(req, status);
httpd_resp_set_type(req, "application/json");
esp_err_t err = httpd_resp_sendstr(req, s ? s : "{}");
free(s);
return err;
}
static esp_err_t send_err(httpd_req_t *req, const char *status, const char *msg)
{
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "error", msg);
return send_json(req, status, o);
}
static cJSON *read_body(httpd_req_t *req)
{
size_t len = req->content_len;
if (len == 0 || len > 4096) {
return NULL;
}
char *buf = malloc(len + 1);
if (!buf) {
return NULL;
}
size_t got = 0;
while (got < len) {
int r = httpd_req_recv(req, buf + got, len - got);
if (r <= 0) {
free(buf);
return NULL;
}
got += (size_t)r;
}
buf[len] = 0;
cJSON *o = cJSON_Parse(buf);
free(buf);
if (!cJSON_IsObject(o)) {
cJSON_Delete(o);
return NULL;
}
return o;
}
static esp_err_t deny(httpd_req_t *req, const char *status, const char *msg)
{
httpd_resp_set_hdr(req, "Connection", "close"); // the body is not read, so the connection cannot be reused
return send_err(req, status, msg);
}
/* ------------------------------------------------------------------ gate */
typedef esp_err_t (*auth_handler_t)(httpd_req_t *req);
static esp_err_t auth_gate(httpd_req_t *req)
{
auth_handler_t fn = (auth_handler_t)(uintptr_t)req->user_ctx;
auth_need_t n = auth_classify(req->uri, req->method);
if (!n.pub) {
char user[33], role[33];
store_lock();
bool enabled = auth_enabled_locked();
bool signed_in = enabled && who(req, user, sizeof user, role, sizeof role);
bool allowed = !enabled || (n.area[0] == '@' ? signed_in : role_perm(role, n.area) >= n.level);
store_unlock();
if (!allowed) {
return signed_in ? deny(req, "403 Forbidden", "not allowed") : deny(req, "401 Unauthorized", "login required");
}
}
return fn(req);
}
esp_err_t auth_register_uri(httpd_handle_t server, const httpd_uri_t *u)
{
httpd_uri_t g = *u;
g.user_ctx = (void *)(uintptr_t)u->handler;
g.handler = auth_gate;
return httpd_register_uri_handler(server, &g);
}
bool auth_can(httpd_req_t *req, const char *area, auth_level_t level)
{
store_lock();
bool enabled = auth_enabled_locked();
store_unlock();
if (!enabled) {
return true;
}
char user[33], role[33];
bool signed_in = who(req, user, sizeof user, role, sizeof role);
if (area[0] == 0 || area[0] == '@') {
return signed_in;
}
return role_perm(role, area) >= level;
}
/* ------------------------------------------------------------------ websockets
* The socket's user is recorded at the handshake; each frame checks the user's current role. */
typedef struct {
int fd;
bool used;
char user[33]; // "" when auth was off at the handshake
} ws_t;
static ws_t s_ws[WS_MAX];
static ws_t *ws_slot(int fd, bool create)
{
ws_t *free_slot = NULL;
for (int i = 0; i < WS_MAX; i++) {
if (s_ws[i].used && s_ws[i].fd == fd) {
return &s_ws[i];
}
if (!s_ws[i].used && !free_slot) {
free_slot = &s_ws[i];
}
}
if (create && free_slot) {
free_slot->used = true;
free_slot->fd = fd;
free_slot->user[0] = 0;
return free_slot;
}
return NULL;
}
esp_err_t auth_ws_admit(httpd_req_t *req, const char *area, auth_level_t level)
{
int fd = httpd_req_to_sockfd(req);
char user[33] = "", role[33] = "";
store_lock();
bool enabled = auth_enabled_locked();
bool ok = !enabled || (who(req, user, sizeof user, role, sizeof role), role_perm(role, area) >= level);
store_unlock();
ws_t *w = ws_slot(fd, ok);
if (!ok || !w) {
if (w) {
w->used = false;
}
ESP_LOGW(TAG, "websocket on fd %d refused", fd);
return ESP_FAIL;
}
snprintf(w->user, sizeof(w->user), "%s", enabled ? user : "");
return ESP_OK;
}
bool auth_ws_allowed(int fd, const char *area, auth_level_t level)
{
store_lock();
bool ok = false;
ws_t *w = ws_slot(fd, false);
if (!auth_enabled_locked()) {
ok = true;
} else if (w && w->user[0]) {
const cJSON *u = cJSON_GetObjectItem(store_coll("user"), w->user);
ok = u && role_perm(str_of(u, "role"), area) >= level;
} else if (w) {
ok = role_perm("guest", area) >= level;
}
store_unlock();
return ok;
}
/* ------------------------------------------------------------------ users and roles */
cJSON *auth_export_users(void)
{
cJSON *out = cJSON_CreateObject();
const cJSON *u = NULL;
store_lock();
cJSON_ArrayForEach(u, store_coll("user"))
{
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "role", str_of(u, "role") ? str_of(u, "role") : "");
cJSON_AddItemToObject(out, u->string, o);
}
store_unlock();
return out;
}
static cJSON *role_record(bool builtin, cJSON *perms)
{
cJSON *r = cJSON_CreateObject();
cJSON_AddItemToObject(r, "perms", perms);
cJSON_AddBoolToObject(r, "builtin", builtin);
return r;
}
// Built-in roles, and an admin from LED_ADMIN_USER / LED_ADMIN_PASSWORD (created, or its password reset)
esp_err_t auth_init(void)
{
store_lock();
cJSON *roles = store_coll("role");
cJSON *all3 = cJSON_CreateObject();
cJSON *guest = cJSON_CreateObject();
for (int i = 0; i < AREA_N; i++) {
cJSON_AddNumberToObject(all3, AREAS[i], AUTH_EDIT);
bool hidden = !strcmp(AREAS[i], "settings") || !strcmp(AREAS[i], "users");
cJSON_AddNumberToObject(guest, AREAS[i], hidden ? AUTH_NONE : AUTH_VIEW);
}
// admin is fixed to edit everywhere; guest is seeded once and can then be edited
obj_set(roles, "admin", role_record(true, all3));
if (!cJSON_GetObjectItem(roles, "guest")) {
cJSON_AddItemToObject(roles, "guest", role_record(true, guest));
} else {
cJSON_Delete(guest);
}
store_save("role");
const char *au = getenv("LED_ADMIN_USER"), *ap = getenv("LED_ADMIN_PASSWORD");
if (au && au[0] && ap && ap[0]) {
if (!valid_name(au) || strlen(ap) < 8 || strlen(ap) > 128) {
ESP_LOGE(TAG, "LED_ADMIN_USER needs 1-32 letters, digits, _ . - ; LED_ADMIN_PASSWORD 8-128 characters");
} else {
cJSON *users = store_coll("user");
uint8_t salt[16], hash[32];
esp_fill_random(salt, sizeof(salt));
pbkdf2(ap, salt, sizeof(salt), PBKDF2_ITER, hash);
cJSON *rec = cJSON_CreateObject();
char hx[65];
cJSON_AddStringToObject(rec, "role", "admin");
to_hex(salt, sizeof(salt), hx);
cJSON_AddStringToObject(rec, "salt", hx);
to_hex(hash, sizeof(hash), hx);
cJSON_AddStringToObject(rec, "hash", hx);
obj_set(users, au, rec);
sess_drop_user(au);
store_save("user");
ESP_LOGI(TAG, "admin user '%s' set from the environment", au);
}
}
store_unlock();
return ESP_OK;
}
static esp_err_t users_list(httpd_req_t *req)
{
cJSON *out = cJSON_CreateArray();
const cJSON *u = NULL;
cJSON_ArrayForEach(u, store_coll("user"))
{
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "username", u->string);
cJSON_AddStringToObject(o, "role", str_of(u, "role") ? str_of(u, "role") : "");
cJSON_AddItemToArray(out, o);
}
return send_json(req, "200 OK", out);
}
static esp_err_t roles_list(httpd_req_t *req)
{
cJSON *out = cJSON_CreateArray();
const cJSON *r = NULL;
cJSON_ArrayForEach(r, store_coll("role"))
{
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "name", r->string);
cJSON_AddBoolToObject(o, "builtin", cJSON_IsTrue(cJSON_GetObjectItem(r, "builtin")));
cJSON_AddItemToObject(o, "perms", cJSON_Duplicate(cJSON_GetObjectItem(r, "perms"), 1));
cJSON_AddItemToArray(out, o);
}
return send_json(req, "200 OK", out);
}
static esp_err_t login(httpd_req_t *req)
{
cJSON *body = read_body(req);
const char *name = body ? str_of(body, "username") : NULL, *pw = body ? str_of(body, "password") : NULL;
if (!name || !pw) {
cJSON_Delete(body);
return send_err(req, "400 Bad Request", "send username and password");
}
int64_t now = esp_timer_get_time();
store_lock();
lock_t *lk = lock_slot(name, false);
if (lk && now < lk->until) {
store_unlock();
cJSON_Delete(body);
return send_err(req, "429 Too Many Requests", "too many attempts for this user, wait and try again");
}
const cJSON *u = cJSON_GetObjectItem(store_coll("user"), name);
uint8_t salt[16], want[32], got[32];
bool ok = false;
if (u && from_hex(str_of(u, "salt"), salt, sizeof salt) && from_hex(str_of(u, "hash"), want, sizeof want)) {
pbkdf2(pw, salt, sizeof salt, PBKDF2_ITER, got);
ok = const_eq(got, want, sizeof got);
} else {
pbkdf2(pw, (const uint8_t *)"0000000000000000", 16, PBKDF2_ITER, got); // same work for unknown users
}
if (!ok) {
lk = lock_slot(name, true);
lk->fails++;
if (lk->fails >= 5) {
int shift = lk->fails - 5 > 4 ? 4 : lk->fails - 5;
int64_t wait = (30LL << shift) > 300 ? 300 : (30LL << shift);
lk->until = now + wait * 1000000;
}
store_unlock();
cJSON_Delete(body);
return send_err(req, "401 Unauthorized", "wrong username or password");
}
if (lk) {
lk->used = false; // a good sign-in clears this name's failures
}
char tok[TOKEN_LEN + 1];
sess_new(name, tok);
cJSON *out = cJSON_CreateObject();
cJSON_AddStringToObject(out, "user", name);
cJSON_AddStringToObject(out, "role", str_of(u, "role") ? str_of(u, "role") : "");
store_unlock();
cJSON_Delete(body);
char ck[220];
char proto[16] = "";
bool secure = httpd_req_get_hdr_value_str(req, "X-Forwarded-Proto", proto, sizeof proto) == ESP_OK && !strcmp(proto, "https");
snprintf(ck, sizeof ck, "%s=%s; Path=/; HttpOnly; SameSite=Strict; Max-Age=2592000%s", COOKIE, tok, secure ? "; Secure" : "");
httpd_resp_set_hdr(req, "Set-Cookie", ck);
return send_json(req, "200 OK", out);
}
static esp_err_t logout(httpd_req_t *req)
{
char tok[TOKEN_LEN + 1];
if (cookie_tok(req, tok)) {
store_lock();
sess_drop_tok(tok);
store_unlock();
}
httpd_resp_set_hdr(req, "Set-Cookie", COOKIE "=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0");
cJSON *o = cJSON_CreateObject();
cJSON_AddBoolToObject(o, "ok", true);
return send_json(req, "200 OK", o);
}
// Sets a password on a user record: a new salt and hash
static void set_password(cJSON *rec, const char *pw)
{
uint8_t salt[16], hash[32];
char hx[65];
esp_fill_random(salt, sizeof salt);
pbkdf2(pw, salt, sizeof salt, PBKDF2_ITER, hash);
to_hex(salt, sizeof salt, hx);
obj_set(rec, "salt", cJSON_CreateString(hx));
to_hex(hash, sizeof hash, hx);
obj_set(rec, "hash", cJSON_CreateString(hx));
}
static bool password_ok(const char *pw)
{
return pw && strlen(pw) >= 8 && strlen(pw) <= 128;
}
static esp_err_t password_put(httpd_req_t *req)
{
cJSON *body = read_body(req);
const char *old = body ? str_of(body, "old") : NULL, *nw = body ? str_of(body, "new") : NULL;
char user[33], role[33];
store_lock();
esp_err_t r;
if (!session_of(req, user, sizeof user, role, sizeof role)) {
r = send_err(req, "401 Unauthorized", "login required");
} else if (!old || !password_ok(nw)) {
r = send_err(req, "400 Bad Request", "send old and new (8 to 128 characters)");
} else {
cJSON *rec = cJSON_GetObjectItem(store_coll("user"), user);
uint8_t salt[16], want[32], got[32];
if (!from_hex(str_of(rec, "salt"), salt, sizeof salt) || !from_hex(str_of(rec, "hash"), want, sizeof want)) {
r = send_err(req, "500 Internal Server Error", "stored password is unreadable");
} else {
pbkdf2(old, salt, sizeof salt, PBKDF2_ITER, got);
if (!const_eq(got, want, sizeof got)) {
r = send_err(req, "403 Forbidden", "current password is wrong");
} else {
set_password(rec, nw);
store_save("user");
cJSON *o = cJSON_CreateObject();
cJSON_AddBoolToObject(o, "ok", true);
r = send_json(req, "200 OK", o);
}
}
}
store_unlock();
cJSON_Delete(body);
return r;
}
static esp_err_t user_create(httpd_req_t *req)
{
cJSON *body = read_body(req);
const char *name = body ? str_of(body, "username") : NULL;
const char *pw = body ? str_of(body, "password") : NULL;
const char *role = body ? str_of(body, "role") : NULL;
esp_err_t r;
store_lock();
if (!body || !valid_name(name)) {
r = send_err(req, "400 Bad Request", "username: 1 to 32 letters, digits, _ . -");
} else if (!password_ok(pw)) {
r = send_err(req, "400 Bad Request", "password: 8 to 128 characters");
} else if (!role || !cJSON_GetObjectItem(store_coll("role"), role)) {
r = send_err(req, "400 Bad Request", "unknown role");
} else if (cJSON_GetObjectItem(store_coll("user"), name)) {
r = send_err(req, "409 Conflict", "that user exists");
} else {
cJSON *rec = cJSON_CreateObject();
cJSON_AddStringToObject(rec, "role", role);
set_password(rec, pw);
cJSON_AddItemToObject(store_coll("user"), name, rec);
store_save("user");
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "username", name);
cJSON_AddStringToObject(o, "role", role);
r = send_json(req, "200 OK", o);
}
store_unlock();
cJSON_Delete(body);
return r;
}
static esp_err_t user_update(httpd_req_t *req, const char *name)
{
cJSON *body = read_body(req);
const char *role = body ? str_of(body, "role") : NULL;
const char *pw = body ? str_of(body, "password") : NULL;
esp_err_t r;
store_lock();
cJSON *rec = cJSON_GetObjectItem(store_coll("user"), name);
if (!body || !rec) {
r = send_err(req, body ? "404 Not Found" : "400 Bad Request", body ? "no such user" : "send role and/or password");
} else if (!role && !pw) {
r = send_err(req, "400 Bad Request", "send role and/or password");
} else if (role && !cJSON_GetObjectItem(store_coll("role"), role)) {
r = send_err(req, "400 Bad Request", "unknown role");
} else if (pw && !password_ok(pw)) {
r = send_err(req, "400 Bad Request", "password: 8 to 128 characters");
} else if (role && managers_after(name, role, 0) + (role_perm(role, "users") >= AUTH_EDIT ? 1 : 0) < 1) {
r = send_err(req, "400 Bad Request", "keep at least one user who can manage users");
} else {
if (role) {
obj_set(rec, "role", cJSON_CreateString(role));
}
if (pw) {
set_password(rec, pw);
sess_drop_user(name);
}
store_save("user");
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "username", name);
cJSON_AddStringToObject(o, "role", str_of(rec, "role") ? str_of(rec, "role") : "");
r = send_json(req, "200 OK", o);
}
store_unlock();
cJSON_Delete(body);
return r;
}
static esp_err_t user_delete(httpd_req_t *req, const char *name)
{
esp_err_t r;
store_lock();
if (!cJSON_GetObjectItem(store_coll("user"), name)) {
r = send_err(req, "404 Not Found", "no such user");
} else if (managers_after(name, NULL, 0) < 1) {
r = send_err(req, "400 Bad Request", "keep at least one user who can manage users");
} else {
cJSON_DeleteItemFromObject(store_coll("user"), name);
sess_drop_user(name);
store_save("user");
cJSON *o = cJSON_CreateObject();
cJSON_AddBoolToObject(o, "ok", true);
r = send_json(req, "200 OK", o);
}
store_unlock();
return r;
}
static esp_err_t role_create(httpd_req_t *req)
{
cJSON *body = read_body(req);
const char *name = body ? str_of(body, "name") : NULL;
const char *err = NULL;
cJSON *perms = body ? perms_from_json(cJSON_GetObjectItem(body, "perms"), &err) : NULL;
esp_err_t r;
store_lock();
if (!body || !valid_name(name)) {
r = send_err(req, "400 Bad Request", "name: 1 to 32 letters, digits, _ . -");
} else if (!perms) {
r = send_err(req, "400 Bad Request", err ? err : "perms missing");
} else if (cJSON_GetObjectItem(store_coll("role"), name)) {
r = send_err(req, "409 Conflict", "that role exists");
} else {
cJSON_AddItemToObject(store_coll("role"), name, role_record(false, perms));
perms = NULL;
store_save("role");
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "name", name);
r = send_json(req, "200 OK", o);
}
cJSON_Delete(perms);
store_unlock();
cJSON_Delete(body);
return r;
}
static esp_err_t role_update(httpd_req_t *req, const char *name)
{
cJSON *body = read_body(req);
const char *err = NULL;
cJSON *perms = body ? perms_from_json(cJSON_GetObjectItem(body, "perms"), &err) : NULL;
esp_err_t r;
store_lock();
cJSON *old = cJSON_GetObjectItem(store_coll("role"), name);
if (!old) {
r = send_err(req, "404 Not Found", "no such role");
} else if (!perms) {
r = send_err(req, "400 Bad Request", err ? err : "send perms");
} else if (!strcmp(name, "admin") && !all_edit(perms)) {
r = send_err(req, "400 Bad Request", "the admin role keeps edit everywhere");
} else if (managers_after(NULL, name, cJSON_GetObjectItem(perms, "users")->valueint) < 1) {
r = send_err(req, "400 Bad Request", "keep at least one user who can manage users");
} else {
obj_set(old, "perms", perms);
perms = NULL;
store_save("role");
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "name", name);
r = send_json(req, "200 OK", o);
}
cJSON_Delete(perms);
store_unlock();
cJSON_Delete(body);
return r;
}
static esp_err_t role_delete(httpd_req_t *req, const char *name)
{
esp_err_t r;
store_lock();
const cJSON *role = cJSON_GetObjectItem(store_coll("role"), name);
bool in_use = false;
const cJSON *u = NULL;
cJSON_ArrayForEach(u, store_coll("user"))
{
if (str_of(u, "role") && !strcmp(str_of(u, "role"), name)) {
in_use = true;
}
}
if (!role) {
r = send_err(req, "404 Not Found", "no such role");
} else if (!strcmp(name, "admin") || !strcmp(name, "guest")) {
r = send_err(req, "400 Bad Request", "the built-in roles cannot be deleted");
} else if (in_use) {
r = send_err(req, "400 Bad Request", "a user has this role: move them first");
} else {
cJSON_DeleteItemFromObject(store_coll("role"), name);
store_save("role");
cJSON *o = cJSON_CreateObject();
cJSON_AddBoolToObject(o, "ok", true);
r = send_json(req, "200 OK", o);
}
store_unlock();
return r;
}
// GET /auth: who is signed in and what they may do (guest's permissions when signed out)
static esp_err_t status_get(httpd_req_t *req)
{
char user[33] = "", role[33] = "";
store_lock();
bool enabled = auth_enabled_locked();
bool signed_in = enabled && session_of(req, user, sizeof user, role, sizeof role);
if (enabled && !signed_in) {
snprintf(role, sizeof role, "%s", "guest");
}
cJSON *o = cJSON_CreateObject();
cJSON_AddBoolToObject(o, "enabled", enabled);
cJSON_AddStringToObject(o, "user", signed_in ? user : "");
cJSON_AddStringToObject(o, "role", enabled ? role : "admin");
cJSON *perms = cJSON_CreateObject();
for (int i = 0; i < AREA_N; i++) {
cJSON_AddNumberToObject(perms, AREAS[i], enabled ? role_perm(role, AREAS[i]) : AUTH_EDIT);
}
cJSON_AddItemToObject(o, "perms", perms);
store_unlock();
return send_json(req, "200 OK", o);
}
static esp_err_t auth_route(httpd_req_t *req)
{
char path[128];
size_t len = strcspn(req->uri, "?");
if (len >= sizeof(path)) {
return send_err(req, "414 URI Too Long", "uri too long");
}
memcpy(path, req->uri, len);
path[len] = 0;
// path is /auth[/<what>[/<name>]]: the first segment is always "auth"
char *s1 = NULL, *s2 = NULL;
char *slash = strchr(path + 1, '/');
if (slash) {
*slash = 0;
s1 = slash + 1;
char *q = strchr(s1, '/');
if (q) {
*q = 0;
s2 = q + 1;
}
}
const char *what = s1 ? s1 : "";
const int m = req->method;
if (!*what && m == HTTP_GET) {
return status_get(req);
}
if (!strcmp(what, "login") && m == HTTP_POST) {
return login(req);
}
if (!strcmp(what, "logout") && m == HTTP_POST) {
return logout(req);
}
if (!strcmp(what, "password") && m == HTTP_PUT) {
return password_put(req);
}
if (!strcmp(what, "users")) {
if (!s2 && m == HTTP_GET) {
return users_list(req);
}
if (!s2 && m == HTTP_POST) {
return user_create(req);
}
if (s2 && m == HTTP_PUT) {
return user_update(req, s2);
}
if (s2 && m == HTTP_DELETE) {
return user_delete(req, s2);
}
}
if (!strcmp(what, "roles")) {
if (!s2 && m == HTTP_GET) {
return roles_list(req);
}
if (!s2 && m == HTTP_POST) {
return role_create(req);
}
if (s2 && m == HTTP_PUT) {
return role_update(req, s2);
}
if (s2 && m == HTTP_DELETE) {
return role_delete(req, s2);
}
}
return send_err(req, "404 Not Found", "unknown auth route");
}
esp_err_t auth_register(httpd_handle_t server)
{
static const httpd_method_t METHODS[] = { HTTP_GET, HTTP_POST, HTTP_PUT, HTTP_DELETE };
for (size_t m = 0; m < 4; m++) {
httpd_uri_t u = { .uri = "/auth*", .method = METHODS[m], .handler = auth_route };
esp_err_t err = auth_register_uri(server, &u);
if (err != ESP_OK) {
return err;
}
}
return ESP_OK;
}