Files
Hodor/main/cam_auth.c
T
Aida_Lashkari 72a2d714ab Add : RTSP audio/video with back channel, and auth
- cam_stream: shared JPEG feed for /pic, /stream and RTSP; RTSP server
  (port 554, TCP) with MJPEG video, G.711 mic audio and an ONVIF-style
  back channel to the speaker
- cam_auth: RTSP Digest login and HTTP Basic / ?key= check on all endpoints
- Mic task feeds HTTP and RTSP with a sticky channel choice
2026-10-08 14:12:48 +03:30

297 lines
9.9 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
*/
#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 "cam_auth.h"
static const char *TAG = "AUTH";
static bool s_enabled = false;
static char s_user[48];
static char s_pass[64];
static char s_ha1[33]; /* md5(user:realm:pass), computed once */
/* ================================================================== */
/* 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 */
/* ================================================================== */
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);
snprintf(s_pass, sizeof(s_pass), "%s", pass ? pass : "");
char tmp[160];
snprintf(tmp, sizeof(tmp), "%s:%s:%s", s_user, CAM_AUTH_REALM, s_pass);
md5_hex(tmp, s_ha1);
ESP_LOGI(TAG, "Authentication enabled for user \"%s\"", s_user);
}
bool cam_auth_enabled(void)
{
return s_enabled;
}
/* ---------------- 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 want[120];
snprintf(want, sizeof(want), "%s:%s", s_user, s_pass);
ok = ct_eq((const char *)dec, want);
}
}
}
/* 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 = ct_eq(v, s_pass);
}
}
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);
}