// Settings transport: WPA2 AP access plus same-origin, per-AP CSRF protection. // The settings coordinator owns validation, persistence and radio handoff. #include "settings_http.h" #include "settings.h" #include "wifi_debug.h" #include #include #include #include #include "cJSON.h" #include "esp_random.h" static char s_boot[9]; static char s_token[33]; static void response_headers(httpd_req_t *req) { httpd_resp_set_type(req, "application/json"); httpd_resp_set_hdr(req, "Cache-Control", "no-store"); httpd_resp_set_hdr(req, "X-Content-Type-Options", "nosniff"); httpd_resp_set_hdr(req, "Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'"); } static esp_err_t error_response(httpd_req_t *req, const char *status, const char *message) { char body[256]; int n = snprintf(body, sizeof(body), "{\"error\":\"%s\"}", message); response_headers(req); httpd_resp_set_status(req, status); httpd_resp_set_hdr(req, "Connection", "close"); if (n > 0 && (size_t)n < sizeof(body)) httpd_resp_send(req, body, n); // Some failures precede reading the body. Close rather than leave unread // bytes on a keep-alive connection or spend time draining an oversized body. return ESP_FAIL; } static bool trusted_request(httpd_req_t *req, bool writing) { char value[80]; if (httpd_req_get_hdr_value_str(req, "Host", value, sizeof(value)) != ESP_OK || (strcmp(value, "192.168.4.1") && strcmp(value, "192.168.4.1:80"))) return false; if (httpd_req_get_hdr_value_len(req, "Origin")) { if (httpd_req_get_hdr_value_str(req, "Origin", value, sizeof(value)) != ESP_OK || (strcmp(value, "http://192.168.4.1") && strcmp(value, "http://192.168.4.1:80"))) return false; } if (httpd_req_get_hdr_value_len(req, "Sec-Fetch-Site")) { if (httpd_req_get_hdr_value_str(req, "Sec-Fetch-Site", value, sizeof(value)) != ESP_OK || (strcmp(value, "same-origin") && strcmp(value, "none"))) return false; } if (!writing) return true; if (httpd_req_get_hdr_value_str(req, "X-CSRF-Token", value, sizeof(value)) != ESP_OK || strcmp(value, s_token)) return false; return true; } static esp_err_t send_snapshot(httpd_req_t *req, const settings_snapshot_t *snapshot) { const repeater_cfg_t *v = &snapshot->values; char ids[88]; size_t used = 0; ids[0] = 0; for (int i = 0; i < v->whitelist_len; i++) { int n = snprintf(ids + used, sizeof(ids) - used, "%s\"%08" PRIX32 "\"", i ? "," : "", v->whitelist[i]); if (n < 0 || (size_t)n >= sizeof(ids) - used) return ESP_FAIL; used += (size_t)n; } char body[1024]; int n = snprintf(body, sizeof(body), "{\"boot_id\":\"%s\",\"revision\":%" PRIu32 ",\"applied_revision\":%" PRIu32 ",\"csrf_token\":\"%s\",\"settings\":{" "\"repeat_delay_ms\":%" PRIu32 ",\"tx_power\":%d,\"repeat_enabled\":%s," "\"verbose\":%s,\"fem_rx_csd\":%s,\"preamble_bits\":%u," "\"duty_budget_ppm\":%" PRIu32 ",\"test_lfield\":%u,\"whitelist\":[%s]," "\"beacon_period_ms\":%" PRIu32 "}}", s_boot, snapshot->revision, snapshot->applied_revision, s_token, v->repeat_delay_ms, (int)v->tx_power_dbm, v->repeat_enabled ? "true" : "false", v->verbose ? "true" : "false", v->fem_rx_csd ? "true" : "false", v->preamble_bits, v->duty_budget_ppm, v->test_lfield, ids, v->beacon_period_ms); if (n < 0 || (size_t)n >= sizeof(body)) return ESP_FAIL; response_headers(req); return httpd_resp_send(req, body, n); } static esp_err_t get_settings(httpd_req_t *req) { if (!trusted_request(req, false)) return error_response(req, "403 Forbidden", "Einstellungen nur unter http://192.168.4.1 öffnen."); settings_snapshot_t snapshot; settings_get_snapshot(&snapshot); return send_snapshot(req, &snapshot); } // cJSON is recursive. Valid requests need only a root object and a whitelist // array, so reject deeper nesting before parsing. Embedded NUL escapes would // otherwise make C-string comparisons accept truncated keys or values. static bool shallow_json(const char *body, size_t len) { bool quoted = false; int depth = 0; for (size_t i = 0; i < len; i++) { unsigned char c = (unsigned char)body[i]; if (!c) return false; if (quoted) { if (c < 0x20) return false; if (c == '\\') { if (++i >= len) return false; if (body[i] == 'u' && i + 4 < len && !memcmp(body + i + 1, "0000", 4)) return false; } else if (c == '"') quoted = false; } else if (c == '"') quoted = true; else if (c == '{' || c == '[') { if (++depth > 2) return false; } else if (c == '}' || c == ']') { if (--depth < 0) return false; } } return !quoted && depth == 0; } static cJSON *receive_body(httpd_req_t *req) { char type[64]; if (httpd_req_get_hdr_value_str(req, "Content-Type", type, sizeof(type)) != ESP_OK || strncasecmp(type, "application/json", 16) || (type[16] && type[16] != ';')) { error_response(req, "415 Unsupported Media Type", "Die Anfrage muss JSON enthalten."); return NULL; } if (!req->content_len || req->content_len > 512 || httpd_req_get_hdr_value_len(req, "Transfer-Encoding")) { error_response(req, "400 Bad Request", "Die Anfrage ist leer, zu groß oder nicht unterstützt."); return NULL; } char body[513]; size_t received = 0; while (received < req->content_len) { int n = httpd_req_recv(req, body + received, req->content_len - received); if (n <= 0) { error_response(req, "408 Request Timeout", "Die Anfrage wurde nicht vollständig empfangen."); return NULL; } received += (size_t)n; } body[received] = 0; cJSON *root = shallow_json(body, received) ? cJSON_ParseWithLengthOpts(body, received + 1, NULL, true) : NULL; if (!cJSON_IsObject(root)) { cJSON_Delete(root); error_response(req, "400 Bad Request", "Ungültige JSON-Anfrage."); return NULL; } return root; } static bool exact_fields(const cJSON *root, const char *const *names, size_t count) { unsigned seen = 0; for (const cJSON *item = root->child; item; item = item->next) { size_t i = 0; while (i < count && strcmp(item->string, names[i])) i++; if (i == count || (seen & (1u << i))) return false; seen |= 1u << i; } return seen == (1u << count) - 1; } static bool correct_boot(const cJSON *root) { const cJSON *boot = cJSON_GetObjectItemCaseSensitive(root, "boot_id"); return cJSON_IsString(boot) && !strcmp(boot->valuestring, s_boot); } typedef enum { VALUE_NUMBER, VALUE_BOOL, VALUE_IDS } value_kind_t; static const struct { const char *name; settings_key_t key; value_kind_t kind; } keys[] = { {"repeat_delay_ms", SETTINGS_REPEAT_DELAY_MS, VALUE_NUMBER}, {"tx_power", SETTINGS_TX_POWER, VALUE_NUMBER}, {"repeat_enabled", SETTINGS_REPEAT_ENABLED, VALUE_BOOL}, {"verbose", SETTINGS_VERBOSE, VALUE_BOOL}, {"fem_rx_csd", SETTINGS_FEM_RX_CSD, VALUE_BOOL}, {"preamble_bits", SETTINGS_PREAMBLE_BITS, VALUE_NUMBER}, {"duty_budget_ppm", SETTINGS_DUTY_BUDGET_PPM, VALUE_NUMBER}, {"test_lfield", SETTINGS_TEST_LFIELD, VALUE_NUMBER}, {"whitelist", SETTINGS_WHITELIST, VALUE_IDS}, {"beacon_period_ms", SETTINGS_BEACON_PERIOD_MS, VALUE_NUMBER}, }; static bool parse_change(const cJSON *root, settings_change_t *change) { const cJSON *key = cJSON_GetObjectItemCaseSensitive(root, "key"); const cJSON *value = cJSON_GetObjectItemCaseSensitive(root, "value"); if (!cJSON_IsString(key)) return false; size_t i = 0; while (i < sizeof(keys) / sizeof(keys[0]) && strcmp(keys[i].name, key->valuestring)) i++; if (i == sizeof(keys) / sizeof(keys[0])) return false; memset(change, 0, sizeof(*change)); change->key = keys[i].key; if (keys[i].kind == VALUE_BOOL) { if (!cJSON_IsBool(value)) return false; change->value = cJSON_IsTrue(value); return true; } if (keys[i].kind == VALUE_NUMBER) { if (!cJSON_IsNumber(value) || !(value->valuedouble >= INT32_MIN && value->valuedouble <= INT32_MAX)) return false; change->value = (int32_t)value->valuedouble; return value->valuedouble == change->value; } if (!cJSON_IsArray(value) || cJSON_GetArraySize(value) > 8) return false; for (const cJSON *id = value->child; id; id = id->next) { if (!cJSON_IsString(id) || strlen(id->valuestring) != 8) return false; uint32_t parsed = 0; for (const char *p = id->valuestring; *p; p++) { unsigned digit; if (*p >= '0' && *p <= '9') digit = *p - '0'; else if (*p >= 'a' && *p <= 'f') digit = *p - 'a' + 10; else if (*p >= 'A' && *p <= 'F') digit = *p - 'A' + 10; else return false; parsed = (parsed << 4) | digit; } change->whitelist[change->whitelist_len++] = parsed; } return true; } static esp_err_t post_settings(httpd_req_t *req) { if (!trusted_request(req, true)) return error_response(req, "403 Forbidden", "Zugriff abgelehnt. Einstellungen neu laden."); cJSON *root = receive_body(req); if (!root) return ESP_FAIL; static const char *const fields[] = {"boot_id", "revision", "key", "value"}; const cJSON *revision = cJSON_GetObjectItemCaseSensitive(root, "revision"); settings_change_t change; bool valid = exact_fields(root, fields, 4) && cJSON_IsNumber(revision) && revision->valuedouble >= 1 && revision->valuedouble <= UINT32_MAX && revision->valuedouble == (uint32_t)revision->valuedouble && parse_change(root, &change); bool boot_ok = correct_boot(root); uint32_t expected = valid ? (uint32_t)revision->valuedouble : 0; cJSON_Delete(root); if (!valid) return error_response(req, "400 Bad Request", "Ungültige Einstellung, Kennung oder Wertart."); if (!boot_ok) return error_response(req, "409 Conflict", "Das Gerät wurde neu gestartet. Einstellungen neu laden."); settings_snapshot_t snapshot; switch (settings_update(&change, expected, &snapshot)) { case SETTINGS_OK: return send_snapshot(req, &snapshot); case SETTINGS_INVALID: return error_response(req, "400 Bad Request", "Wert außerhalb des erlaubten Bereichs oder doppelte Kennung."); case SETTINGS_CONFLICT: return error_response(req, "409 Conflict", "Einstellungen wurden inzwischen geändert. Neu laden und prüfen."); case SETTINGS_STORAGE_ERROR: return error_response(req, "503 Service Unavailable", "Speichern fehlgeschlagen. Die Einstellung wurde nicht übernommen."); case SETTINGS_BUSY: return error_response(req, "503 Service Unavailable", "Eine andere Änderung läuft. Neu laden und erneut versuchen."); default: return error_response(req, "500 Internal Server Error", "Die Einstellung konnte nicht übernommen werden."); } } static esp_err_t disable_wifi(httpd_req_t *req) { if (!trusted_request(req, true)) return error_response(req, "403 Forbidden", "Zugriff abgelehnt. Einstellungen neu laden."); cJSON *root = receive_body(req); if (!root) return ESP_FAIL; static const char *const fields[] = {"boot_id"}; bool valid = exact_fields(root, fields, 1); bool boot_ok = correct_boot(root); cJSON_Delete(root); if (!valid) return error_response(req, "400 Bad Request", "Ungültige WLAN-Anfrage."); if (!boot_ok) return error_response(req, "409 Conflict", "Das Gerät wurde neu gestartet. Einstellungen neu laden."); response_headers(req); esp_err_t err = httpd_resp_send(req, "{\"ok\":true}", HTTPD_RESP_USE_STRLEN); if (err == ESP_OK) wifi_debug_disable(); return err; } esp_err_t settings_http_register(httpd_handle_t server, uint32_t boot_id) { snprintf(s_boot, sizeof(s_boot), "%08" PRIx32, boot_id); uint8_t random[16]; esp_fill_random(random, sizeof(random)); // Wi-Fi hardware entropy is active. for (size_t i = 0; i < sizeof(random); i++) snprintf(s_token + i * 2, 3, "%02x", random[i]); const httpd_uri_t routes[] = { {.uri = "/api/settings", .method = HTTP_GET, .handler = get_settings}, {.uri = "/api/settings", .method = HTTP_POST, .handler = post_settings}, {.uri = "/api/wifi/disable", .method = HTTP_POST, .handler = disable_wifi}, }; for (size_t i = 0; i < sizeof(routes) / sizeof(routes[0]); i++) { esp_err_t err = httpd_register_uri_handler(server, &routes[i]); if (err != ESP_OK) return err; } return ESP_OK; }