Files
Hodor/main/cam_auth.c
T
Aida_Lashkari 194671d387 Add BOOT-button entry to the setup portal and gate the Wi-Fi card behind login
Hold BOOT (GPIO0) for 10s while running to reboot into the captive
portal without needing the current media login (physical access is the
proof). This also covers the "forgotten login" case.

button.c (new)
- button_task polls GPIO0 (pull-up, 50 ms), ignores a press held since
  boot so download-mode entry is unaffected, and calls
  wifi_request_portal_physical() after 10s.
- Started from app_main() right after wifi_start_provisioning_if_needed(),
  only when not provisioning, so it also works while the station is
  retrying an unreachable network.

wifi.c
- wifi_request_portal_physical(): stores a one-shot "portal requested by
  button" flag in NVS (namespace "portal") and restarts. NVS is used
  instead of RTC_DATA_ATTR because the flag was lost across the reset
  on this board.
- wifi_start_provisioning_if_needed(): reads and erases the flag at boot
  (portal_flag_take) and sets s_physical for that portal session only.
  Logs the reset reason.
- Portal without the button (30 failed reconnects, wifi_request_portal())
  stays non-physical and asks for the current login.
- /save (Wi-Fi card) now requires cam_auth_verify() unless s_physical.
- /auth uses cam_auth_set() when s_physical, else cam_auth_change().
- Shared lockout: 5 wrong logins block /save and /auth until restart
  (not applied when s_physical). Failed attempts are delayed by 1 s.
- Physical portal times out after 180 s (normal portal: 300 s).
- Root page gets "var PHYS=0/1" injected before its script via chunked
  send; with PHYS=1 the "current login" fields are hidden and a banner
  is shown.
- html: added current-login fields (wu/wp) to the Wi-Fi form, wrapped
  current-login fields in .cur, /save errors are shown to the user.
- read_body()/send_text() moved above the handlers.

cam_auth.c
- New cam_auth_set(): validates and stores a new login with no check of
  the current one. cam_auth_change() now = cam_auth_verify() +
  cam_auth_set().

Requirements
- cam_auth_load() must run before wifi_start_provisioning_if_needed(),
  otherwise cam_auth_verify() treats auth as disabled and accepts any
  login.
- cam_auth.h: declare cam_auth_set(); declare
  wifi_request_portal_physical() where button.c can see it.

Tested on board: long press reboots into the AP "ESP32_Setup" instead of
reconnecting to the stored network. Not yet tested: Wi-Fi card login
gating, lockout, 180 s timeout, portal page rendering on a phone.
2026-10-11 15:26:53 +03:30

416 lines
14 KiB
C

/*
* cam_auth.c
* - tiny self-contained MD5 (no mbedTLS dependency, works on every ESP-IDF version)
* - RTSP Digest authentication (RFC 2069 style, no qop: what ffmpeg, VLC and go2rtc speak)
* - HTTP check: "Authorization: Basic" header or "?key=" query parameter
* - login stored in NVS as user name + MD5 hash (no plain password in flash),
* changeable at runtime:
* cam_auth_change() after verifying the current login
* cam_auth_set() WITHOUT verifying it (only for the BOOT-button portal, where
* physical access to the device is the proof)
*
* cam_auth.h must declare (add the last one):
* bool cam_auth_verify(const char *user, const char *pass);
* cam_auth_result_t cam_auth_change(const char *old_user, const char *old_pass,
* const char *new_user, const char *new_pass);
* cam_auth_result_t cam_auth_set(const char *new_user, const char *new_pass);
*/
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include <strings.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "esp_random.h"
#include "nvs_flash.h"
#include "nvs.h"
#include "cam_auth.h"
static const char *TAG = "AUTH";
static bool s_enabled = false;
static char s_user[48];
static char s_ha1[33]; /* md5(user:realm:pass); the password itself is never kept */
#define AUTH_NS "cam_auth" /* NVS namespace: keys "user" and "ha1" */
/* ================================================================== */
/* MD5 (RFC 1321) */
/* ================================================================== */
typedef struct {
uint32_t a, b, c, d;
uint64_t bytes;
uint8_t buf[64];
} md5_ctx;
static const uint32_t MD5_K[64] = {
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391
};
static const uint8_t MD5_S[64] = {
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21
};
#define ROL32(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
static void md5_block(md5_ctx *c, const uint8_t *p)
{
uint32_t M[16];
for (int i = 0; i < 16; i++)
M[i] = (uint32_t)p[4 * i] | ((uint32_t)p[4 * i + 1] << 8) |
((uint32_t)p[4 * i + 2] << 16) | ((uint32_t)p[4 * i + 3] << 24);
uint32_t A = c->a, B = c->b, C = c->c, D = c->d;
for (int i = 0; i < 64; i++) {
uint32_t F;
int g;
if (i < 16) { F = (B & C) | (~B & D); g = i; }
else if (i < 32) { F = (D & B) | (~D & C); g = (5 * i + 1) & 15; }
else if (i < 48) { F = B ^ C ^ D; g = (3 * i + 5) & 15; }
else { F = C ^ (B | ~D); g = (7 * i) & 15; }
F = F + A + MD5_K[i] + M[g];
A = D;
D = C;
C = B;
B = B + ROL32(F, MD5_S[i]);
}
c->a += A; c->b += B; c->c += C; c->d += D;
}
static void md5_init(md5_ctx *c)
{
c->a = 0x67452301; c->b = 0xefcdab89; c->c = 0x98badcfe; c->d = 0x10325476;
c->bytes = 0;
}
static void md5_update(md5_ctx *c, const void *data, size_t n)
{
const uint8_t *p = data;
size_t have = (size_t)(c->bytes & 63);
c->bytes += n;
if (have) {
size_t take = 64 - have;
if (take > n) take = n;
memcpy(c->buf + have, p, take);
p += take;
n -= take;
if (have + take == 64) md5_block(c, c->buf);
else return;
}
while (n >= 64) { md5_block(c, p); p += 64; n -= 64; }
if (n) memcpy(c->buf, p, n);
}
static void md5_final(md5_ctx *c, uint8_t out[16])
{
uint64_t bits = c->bytes * 8;
static const uint8_t pad[64] = { 0x80 };
size_t have = (size_t)(c->bytes & 63);
size_t padlen = (have < 56) ? (56 - have) : (120 - have);
md5_update(c, pad, padlen);
uint8_t len[8];
for (int i = 0; i < 8; i++) len[i] = (uint8_t)(bits >> (8 * i));
md5_update(c, len, 8);
uint32_t v[4] = { c->a, c->b, c->c, c->d };
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++) out[4 * i + j] = (uint8_t)(v[i] >> (8 * j));
}
/* md5 of a string, as 32 lowercase hex characters + NUL */
static void md5_hex(const char *s, char out[33])
{
md5_ctx c;
uint8_t d[16];
md5_init(&c);
md5_update(&c, s, strlen(s));
md5_final(&c, d);
for (int i = 0; i < 16; i++) sprintf(out + 2 * i, "%02x", d[i]);
}
/* ================================================================== */
/* Helpers */
/* ================================================================== */
static bool ct_eq(const char *a, const char *b) /* constant-time string compare */
{
size_t la = strlen(a), lb = strlen(b);
unsigned d = (unsigned)(la ^ lb);
size_t n = la < lb ? la : lb;
for (size_t i = 0; i < n; i++) d |= (unsigned char)a[i] ^ (unsigned char)b[i];
return d == 0;
}
static int b64_val(char c)
{
if (c >= 'A' && c <= 'Z') return c - 'A';
if (c >= 'a' && c <= 'z') return c - 'a' + 26;
if (c >= '0' && c <= '9') return c - '0' + 52;
if (c == '+') return 62;
if (c == '/') return 63;
return -1;
}
static size_t b64_decode(const char *in, uint8_t *out, size_t outmax)
{
size_t n = 0;
uint32_t acc = 0;
int bits = 0;
for (; *in && *in != '='; in++) {
int v = b64_val(*in);
if (v < 0) return 0;
acc = (acc << 6) | (uint32_t)v;
bits += 6;
if (bits >= 8) {
bits -= 8;
if (n >= outmax) return 0;
out[n++] = (uint8_t)(acc >> bits);
}
}
return n;
}
/* ================================================================== */
/* Public API */
/* ================================================================== */
static void make_ha1(const char *user, const char *pass, char out[33])
{
char tmp[200];
snprintf(tmp, sizeof(tmp), "%s:%s:%s", user, CAM_AUTH_REALM, pass);
md5_hex(tmp, out);
}
void cam_auth_init(const char *user, const char *pass)
{
s_enabled = (user && *user);
if (!s_enabled) {
ESP_LOGW(TAG, "Authentication DISABLED");
return;
}
snprintf(s_user, sizeof(s_user), "%s", user);
make_ha1(s_user, pass ? pass : "", s_ha1);
ESP_LOGI(TAG, "Authentication enabled for user \"%s\"", s_user);
}
bool cam_auth_enabled(void)
{
return s_enabled;
}
bool cam_auth_verify(const char *user, const char *pass)
{
if (!s_enabled) return true;
if (!user || !pass) return false;
char ha1[33];
make_ha1(user, pass, ha1);
bool u_ok = ct_eq(user, s_user); /* evaluate both: no early exit */
bool p_ok = ct_eq(ha1, s_ha1);
return u_ok && p_ok;
}
/* ---------------- Stored login (NVS) ---------------- */
static bool valid_user(const char *u) /* 3-31 chars: letters, digits . _ - */
{
size_t n = strlen(u);
if (n < 3 || n > 31) return false;
for (size_t i = 0; i < n; i++) {
char c = u[i];
bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
c == '.' || c == '_' || c == '-';
if (!ok) return false;
}
return true;
}
static bool valid_pass(const char *p) /* 8-32 chars: letters and digits */
{
size_t n = strlen(p);
if (n < 8 || n > 32) return false;
for (size_t i = 0; i < n; i++) {
char c = p[i];
bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
if (!ok) return false;
}
return true;
}
static bool store_save(const char *user, const char *ha1)
{
nvs_handle_t h;
if (nvs_open(AUTH_NS, NVS_READWRITE, &h) != ESP_OK) return false;
bool ok = nvs_set_str(h, "user", user) == ESP_OK &&
nvs_set_str(h, "ha1", ha1) == ESP_OK &&
nvs_commit(h) == ESP_OK;
nvs_close(h);
return ok;
}
void cam_auth_load(const char *default_user, const char *default_pass)
{
esp_err_t e = nvs_flash_init(); /* harmless if already initialised */
if (e == ESP_ERR_NVS_NO_FREE_PAGES || e == ESP_ERR_NVS_NEW_VERSION_FOUND) {
nvs_flash_erase();
nvs_flash_init();
}
nvs_handle_t h;
if (nvs_open(AUTH_NS, NVS_READONLY, &h) == ESP_OK) {
char u[48] = {0}, ha[33] = {0};
size_t ul = sizeof(u), hl = sizeof(ha);
bool ok = nvs_get_str(h, "user", u, &ul) == ESP_OK &&
nvs_get_str(h, "ha1", ha, &hl) == ESP_OK &&
u[0] != 0 && strlen(ha) == 32;
nvs_close(h);
if (ok) {
s_enabled = true;
snprintf(s_user, sizeof(s_user), "%s", u);
memcpy(s_ha1, ha, sizeof(s_ha1));
ESP_LOGI(TAG, "Loaded stored login for user \"%s\"", s_user);
return;
}
}
cam_auth_init(default_user, default_pass);
ESP_LOGW(TAG, "Using the built-in default login: change it on the setup page");
}
/* Validates the new login, stores it and makes it active. No check of the current login. */
cam_auth_result_t cam_auth_set(const char *new_user, const char *new_pass)
{
if (!new_user || !new_pass || !valid_user(new_user) || !valid_pass(new_pass))
return CAM_AUTH_BAD_NEW;
char ha1[33];
make_ha1(new_user, new_pass, ha1);
if (!store_save(new_user, ha1)) return CAM_AUTH_STORE_FAILED;
s_enabled = true;
snprintf(s_user, sizeof(s_user), "%s", new_user);
memcpy(s_ha1, ha1, sizeof(s_ha1));
ESP_LOGI(TAG, "Login changed, new user \"%s\"", s_user);
return CAM_AUTH_OK;
}
cam_auth_result_t cam_auth_change(const char *old_user, const char *old_pass,
const char *new_user, const char *new_pass)
{
if (!cam_auth_verify(old_user, old_pass)) return CAM_AUTH_BAD_CURRENT;
return cam_auth_set(new_user, new_pass);
}
/* ---------------- HTTP ---------------- */
bool cam_http_check(httpd_req_t *req)
{
if (!s_enabled) return true;
bool ok = false;
/* 1) Authorization: Basic base64(user:pass) (Home Assistant, NVRs, browsers' login box) */
size_t hl = httpd_req_get_hdr_value_len(req, "Authorization");
if (hl > 6 && hl < 200) {
char h[200];
if (httpd_req_get_hdr_value_str(req, "Authorization", h, sizeof(h)) == ESP_OK &&
strncasecmp(h, "Basic ", 6) == 0) {
uint8_t dec[130];
size_t dl = b64_decode(h + 6, dec, sizeof(dec) - 1);
if (dl > 0) {
dec[dl] = 0;
char *colon = strchr((char *)dec, ':');
if (colon) {
*colon = 0;
ok = cam_auth_verify((const char *)dec, colon + 1);
}
}
}
}
/* 2) ?key=<password> (web pages: works for <img>, fetch() without CORS preflight) */
if (!ok) {
char q[160], v[80];
if (httpd_req_get_url_query_str(req, q, sizeof(q)) == ESP_OK &&
httpd_query_key_value(q, "key", v, sizeof(v)) == ESP_OK) {
ok = cam_auth_verify(s_user, v);
}
}
if (!ok) {
ESP_LOGW(TAG, "HTTP request refused: %s", req->uri);
vTaskDelay(pdMS_TO_TICKS(300)); /* slows down password guessing */
httpd_resp_set_status(req, "401 Unauthorized");
httpd_resp_set_hdr(req, "WWW-Authenticate", "Basic realm=\"" CAM_AUTH_REALM "\"");
httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
httpd_resp_set_type(req, "text/plain");
httpd_resp_send(req, "Unauthorized", HTTPD_RESP_USE_STRLEN);
}
return ok;
}
/* ---------------- RTSP Digest ---------------- */
void cam_rtsp_make_nonce(char out[33])
{
for (int i = 0; i < 4; i++) sprintf(out + 8 * i, "%08x", (unsigned)esp_random());
out[32] = 0;
}
/* value of key="..." (or key=value) inside a Digest parameter list */
static bool dig_field(const char *s, const char *key, char *out, size_t n)
{
size_t kl = strlen(key);
for (const char *p = s; *p; p++) {
if ((p == s || p[-1] == ' ' || p[-1] == ',') &&
strncasecmp(p, key, kl) == 0 && p[kl] == '=') {
p += kl + 1;
size_t i = 0;
if (*p == '"') {
p++;
while (*p && *p != '"' && i < n - 1) out[i++] = *p++;
} else {
while (*p && *p != ',' && *p != ' ' && *p != '\r' && *p != '\n' && i < n - 1) out[i++] = *p++;
}
out[i] = 0;
return true;
}
}
return false;
}
bool cam_rtsp_digest_ok(const char *method, const char *authz, const char *nonce)
{
if (!s_enabled) return true;
if (!authz || strncasecmp(authz, "Digest ", 7) != 0) return false;
const char *params = authz + 7;
char user[48], realm[48], n[48], uri[200], resp[48];
if (!dig_field(params, "username", user, sizeof(user)) ||
!dig_field(params, "realm", realm, sizeof(realm)) ||
!dig_field(params, "nonce", n, sizeof(n)) ||
!dig_field(params, "uri", uri, sizeof(uri)) ||
!dig_field(params, "response", resp, sizeof(resp))) return false;
if (!ct_eq(user, s_user) || !ct_eq(realm, CAM_AUTH_REALM) || !ct_eq(n, nonce)) return false;
char tmp[320], ha2[33], expect[33];
snprintf(tmp, sizeof(tmp), "%s:%s", method, uri); /* HA2 uses the real method */
md5_hex(tmp, ha2);
snprintf(tmp, sizeof(tmp), "%s:%s:%s", s_ha1, nonce, ha2);
md5_hex(tmp, expect);
return ct_eq(resp, expect);
}