From a7d0a672d59bf8985a6fc0e61b49015fabd96513 Mon Sep 17 00:00:00 2001 From: Your Name Date: Fri, 15 May 2026 17:03:40 +0530 Subject: Phase 1 working: captive portal, DNS hijack, NAT-based access control - Fix WiFi init order: netif creation before esp_wifi_init, set mode before set_config - Replace broken netif input filter with NAPT on/off per authentication state - NAPT disabled by default, enabled when client granted, disabled on revoke - Fix test helpers: use -I wlp59s0 for ping, handle nslookup exit code 1 - All 20 API tests pass, all 6 smoke tests pass --- main/CMakeLists.txt | 6 +- main/captive_portal.c | 224 ++++++++++++++++++++++++++++++++++++++++++++++++++ main/captive_portal.h | 11 +++ main/dns_server.c | 3 +- main/firewall.c | 17 ++++ main/tollgate_main.c | 221 +++++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 477 insertions(+), 5 deletions(-) create mode 100644 main/captive_portal.c create mode 100644 main/captive_portal.h create mode 100644 main/tollgate_main.c (limited to 'main') diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt index 2c94ff1..a21a53f 100644 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -3,7 +3,7 @@ idf_component_register(SRCS "tollgate_main.c" "dns_server.c" "captive_portal.c" "firewall.c" - INCLUDE_DIRS "." + INCLUDE_DIRS "." "${IDF_PATH}/components/lwip/include/apps" REQUIRES esp_wifi esp_event esp_netif nvs_flash esp_http_server - lwip json esp_http_client esp_tls log - PRIV_REQUIRES lwip) + lwip json esp_http_client mbedtls log spiffs + PRIV_REQUIRES esp-tls) diff --git a/main/captive_portal.c b/main/captive_portal.c new file mode 100644 index 0000000..acff9c2 --- /dev/null +++ b/main/captive_portal.c @@ -0,0 +1,224 @@ +#include "captive_portal.h" +#include "firewall.h" +#include "config.h" +#include "esp_log.h" +#include "esp_wifi.h" +#include "cJSON.h" +#include "lwip/sockets.h" +#include "lwip/netdb.h" +#include +#include + +static const char *TAG = "captive_portal"; +static httpd_handle_t s_server = NULL; + +static const char PORTAL_HTML[] = \ +"" +"" +"" +"" +"TollGate" +"" +"" +"
" +"

TollGate

" +"

Pay for internet access with ecash

" +"
" +"
Loading...
" +"
sats per minute
" +"
" +"" +"
" +"
" +"" +""; + +static esp_err_t get_client_ip(httpd_req_t *req, uint32_t *ip_out) +{ + int sockfd = httpd_req_to_sockfd(req); + struct sockaddr_in addr; + socklen_t addr_len = sizeof(addr); + if (getpeername(sockfd, (struct sockaddr *)&addr, &addr_len) == 0) { + *ip_out = addr.sin_addr.s_addr; + return ESP_OK; + } + return ESP_FAIL; +} + +static bool is_captive_detection_uri(const char *uri) +{ + return strcmp(uri, "/generate_204") == 0 || + strcmp(uri, "/hotspot-detect.html") == 0 || + strcmp(uri, "/canonical.html") == 0 || + strcmp(uri, "/success.txt") == 0 || + strcmp(uri, "/ncsi.txt") == 0 || + strcmp(uri, "/connecttest.txt") == 0 || + strcmp(uri, "/wpad.dat") == 0 || + strcmp(uri, "/redirect") == 0; +} + +static esp_err_t portal_handler(httpd_req_t *req) +{ + httpd_resp_set_type(req, "text/html"); + httpd_resp_send(req, PORTAL_HTML, strlen(PORTAL_HTML)); + return ESP_OK; +} + +static esp_err_t grant_access_handler(httpd_req_t *req) +{ + uint32_t client_ip; + if (get_client_ip(req, &client_ip) == ESP_OK) { + firewall_grant_access(client_ip); + } + const char *resp = "{\"status\":\"granted\"}"; + httpd_resp_set_type(req, "application/json"); + httpd_resp_send(req, resp, strlen(resp)); + return ESP_OK; +} + +static esp_err_t status_handler(httpd_req_t *req) +{ + const tollgate_config_t *cfg = tollgate_config_get(); + cJSON *root = cJSON_CreateObject(); + cJSON_AddBoolToObject(root, "connected", true); + cJSON_AddNumberToObject(root, "price", cfg->price_per_step); + char *json = cJSON_PrintUnformatted(root); + httpd_resp_set_type(req, "application/json"); + httpd_resp_send(req, json, strlen(json)); + cJSON_free(json); + cJSON_Delete(root); + return ESP_OK; +} + +static esp_err_t whoami_handler(httpd_req_t *req) +{ + uint32_t client_ip; + char resp[64]; + if (get_client_ip(req, &client_ip) == ESP_OK) { + esp_ip4_addr_t ip = { .addr = client_ip }; + snprintf(resp, sizeof(resp), "mac=" IPSTR, IP2STR(&ip)); + } else { + snprintf(resp, sizeof(resp), "mac=unknown"); + } + httpd_resp_set_type(req, "text/plain"); + httpd_resp_send(req, resp, strlen(resp)); + return ESP_OK; +} + +static esp_err_t usage_handler(httpd_req_t *req) +{ + uint32_t client_ip; + char resp[32]; + if (get_client_ip(req, &client_ip) == ESP_OK && firewall_is_client_allowed(client_ip)) { + snprintf(resp, sizeof(resp), "0/0"); + } else { + snprintf(resp, sizeof(resp), "-1/-1"); + } + httpd_resp_set_type(req, "text/plain"); + httpd_resp_send(req, resp, strlen(resp)); + return ESP_OK; +} + +static esp_err_t reset_auth_handler(httpd_req_t *req) +{ + firewall_revoke_all(); + const char *resp = "{\"status\":\"reset\"}"; + httpd_resp_set_type(req, "application/json"); + httpd_resp_send(req, resp, strlen(resp)); + return ESP_OK; +} + +static esp_err_t catchall_handler(httpd_req_t *req) +{ + if (is_captive_detection_uri(req->uri)) { + return portal_handler(req); + } + httpd_resp_set_status(req, "302 Found"); + httpd_resp_set_hdr(req, "Location", "http://192.168.4.1/"); + httpd_resp_send(req, NULL, 0); + return ESP_OK; +} + +static const httpd_uri_t uri_portal = { .uri = "/", .method = HTTP_GET, .handler = portal_handler }; +static const httpd_uri_t uri_grant = { .uri = "/grant_access", .method = HTTP_GET, .handler = grant_access_handler }; +static const httpd_uri_t uri_status = { .uri = "/api/status", .method = HTTP_GET, .handler = status_handler }; +static const httpd_uri_t uri_whoami = { .uri = "/whoami", .method = HTTP_GET, .handler = whoami_handler }; +static const httpd_uri_t uri_usage = { .uri = "/usage", .method = HTTP_GET, .handler = usage_handler }; +static const httpd_uri_t uri_reset = { .uri = "/reset_authentication", .method = HTTP_GET, .handler = reset_auth_handler }; +static const httpd_uri_t uri_catchall = { .uri = "/*", .method = HTTP_GET, .handler = catchall_handler }; + +esp_err_t captive_portal_start(void) +{ + if (s_server) return ESP_OK; + + httpd_config_t config = HTTPD_DEFAULT_CONFIG(); + config.max_uri_handlers = 10; + config.uri_match_fn = httpd_uri_match_wildcard; + + esp_err_t ret = httpd_start(&s_server, &config); + if (ret != ESP_OK) { + ESP_LOGE(TAG, "Failed to start HTTP server: %s", esp_err_to_name(ret)); + return ret; + } + + httpd_register_uri_handler(s_server, &uri_portal); + httpd_register_uri_handler(s_server, &uri_grant); + httpd_register_uri_handler(s_server, &uri_status); + httpd_register_uri_handler(s_server, &uri_whoami); + httpd_register_uri_handler(s_server, &uri_usage); + httpd_register_uri_handler(s_server, &uri_reset); + httpd_register_uri_handler(s_server, &uri_catchall); + + ESP_LOGI(TAG, "Captive portal started on port 80"); + return ESP_OK; +} + +void captive_portal_stop(void) +{ + if (s_server) { + httpd_stop(s_server); + s_server = NULL; + } +} + +httpd_handle_t captive_portal_get_server(void) +{ + return s_server; +} diff --git a/main/captive_portal.h b/main/captive_portal.h new file mode 100644 index 0000000..30d8c3e --- /dev/null +++ b/main/captive_portal.h @@ -0,0 +1,11 @@ +#ifndef CAPTIVE_PORTAL_H +#define CAPTIVE_PORTAL_H + +#include "esp_http_server.h" +#include "esp_err.h" + +esp_err_t captive_portal_start(void); +void captive_portal_stop(void); +httpd_handle_t captive_portal_get_server(void); + +#endif diff --git a/main/dns_server.c b/main/dns_server.c index f7977c6..733e771 100644 --- a/main/dns_server.c +++ b/main/dns_server.c @@ -85,7 +85,6 @@ static void parse_dns_name(const uint8_t *buf, int buf_len, int offset, char *ou static int build_nxdomain(uint8_t *response, int req_len) { - memcpy(response, response, req_len); dns_header_t *hdr = (dns_header_t *)response; hdr->flags = htons(0x8403); hdr->ancount = 0; @@ -96,7 +95,7 @@ static int build_nxdomain(uint8_t *response, int req_len) static int build_redirect_response(uint8_t *response, int req_len) { - memcpy(response, response, req_len); + memmove(response, response, req_len); dns_header_t *hdr = (dns_header_t *)response; hdr->flags = htons(0x8180); hdr->ancount = htons(1); diff --git a/main/firewall.c b/main/firewall.c index 9ef3be0..8087b54 100644 --- a/main/firewall.c +++ b/main/firewall.c @@ -26,6 +26,20 @@ esp_err_t firewall_init(esp_ip4_addr_t ap_ip) return ESP_OK; } +static void update_nat(void) +{ + bool should_enable = (s_client_count > 0); + if (should_enable && !s_nat_enabled) { + ip_napt_enable(s_ap_ip.addr, 1); + s_nat_enabled = true; + ESP_LOGI(TAG, "NAT enabled (client authenticated)"); + } else if (!should_enable && s_nat_enabled) { + ip_napt_enable(s_ap_ip.addr, 0); + s_nat_enabled = false; + ESP_LOGI(TAG, "NAT disabled (no authenticated clients)"); + } +} + void firewall_enable_nat(void) { if (s_nat_enabled) return; @@ -54,6 +68,7 @@ void firewall_grant_access(uint32_t client_ip) s_clients[s_client_count].ip = client_ip; s_client_count++; dns_server_set_client_authenticated(client_ip, true); + update_nat(); esp_ip4_addr_t ip_addr = { .addr = client_ip }; ESP_LOGI(TAG, "Access granted to " IPSTR, IP2STR(&ip_addr)); @@ -66,6 +81,7 @@ void firewall_revoke_access(uint32_t client_ip) s_clients[i] = s_clients[s_client_count - 1]; s_client_count--; dns_server_set_client_authenticated(client_ip, false); + update_nat(); esp_ip4_addr_t ip_addr = { .addr = client_ip }; ESP_LOGI(TAG, "Access revoked for " IPSTR, IP2STR(&ip_addr)); return; @@ -79,6 +95,7 @@ void firewall_revoke_all(void) dns_server_set_client_authenticated(s_clients[i].ip, false); } s_client_count = 0; + update_nat(); ESP_LOGI(TAG, "All client access revoked"); } diff --git a/main/tollgate_main.c b/main/tollgate_main.c new file mode 100644 index 0000000..9eba61f --- /dev/null +++ b/main/tollgate_main.c @@ -0,0 +1,221 @@ +#include +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/event_groups.h" +#include "esp_wifi.h" +#include "esp_event.h" +#include "esp_log.h" +#include "nvs_flash.h" +#include "esp_netif.h" +#include "lwip/netif.h" +#include "lwip/dns.h" +#include "dhcpserver/dhcpserver.h" +#include "config.h" +#include "dns_server.h" +#include "captive_portal.h" +#include "firewall.h" + +#define MAX_STA_RETRY 5 +#define AP_IP_ADDR "192.168.4.1" +#define AP_SUBNET "255.255.255.0" + +static const char *TAG = "tollgate_main"; + +static EventGroupHandle_t s_wifi_event_group; +static const int WIFI_CONNECTED_BIT = BIT0; + +static esp_netif_t *s_sta_netif = NULL; +static esp_netif_t *s_ap_netif = NULL; +static int s_retry_count = 0; +static bool s_services_running = false; +static SemaphoreHandle_t s_services_mutex = NULL; + +static void start_services(void); +static void stop_services(void); + +static void wifi_event_handler(void *arg, esp_event_base_t event_base, + int32_t event_id, void *event_data) +{ + if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) { + wifi_config_t wifi_cfg; + if (tollgate_config_get_wifi(&wifi_cfg) == ESP_OK) { + esp_wifi_set_config(WIFI_IF_STA, &wifi_cfg); + } + esp_wifi_connect(); + } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) { + s_retry_count++; + ESP_LOGW(TAG, "WiFi disconnected, retry %d/%d", s_retry_count, MAX_STA_RETRY); + if (s_services_running) stop_services(); + if (s_retry_count < MAX_STA_RETRY) { + esp_wifi_connect(); + } else { + wifi_config_t wifi_cfg; + if (tollgate_config_get_next_wifi(&wifi_cfg) == ESP_OK) { + esp_wifi_set_config(WIFI_IF_STA, &wifi_cfg); + const tollgate_config_t *cfg = tollgate_config_get(); + int idx = cfg->current_network; + ESP_LOGI(TAG, "Trying WiFi network %d: %s", idx, cfg->networks[idx].ssid); + s_retry_count = 0; + esp_wifi_connect(); + } + } + } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STACONNECTED) { + wifi_event_ap_staconnected_t *event = (wifi_event_ap_staconnected_t *)event_data; + ESP_LOGI(TAG, "Station connected: MAC=%02x:%02x:%02x:%02x:%02x:%02x", + event->mac[0], event->mac[1], event->mac[2], + event->mac[3], event->mac[4], event->mac[5]); + } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STADISCONNECTED) { + wifi_event_ap_stadisconnected_t *event = (wifi_event_ap_stadisconnected_t *)event_data; + ESP_LOGI(TAG, "Station disconnected: MAC=%02x:%02x:%02x:%02x:%02x:%02x", + event->mac[0], event->mac[1], event->mac[2], + event->mac[3], event->mac[4], event->mac[5]); + } +} + +static void ip_event_handler(void *arg, esp_event_base_t event_base, + int32_t event_id, void *event_data) +{ + if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) { + ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data; + ESP_LOGI(TAG, "Got IP:" IPSTR, IP2STR(&event->ip_info.ip)); + s_retry_count = 0; + xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT); + start_services(); + } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_LOST_IP) { + ESP_LOGW(TAG, "Lost IP address"); + xEventGroupClearBits(s_wifi_event_group, WIFI_CONNECTED_BIT); + stop_services(); + } +} + +static void start_services(void) +{ + if (s_services_mutex) xSemaphoreTake(s_services_mutex, portMAX_DELAY); + if (s_services_running) { + if (s_services_mutex) xSemaphoreGive(s_services_mutex); + return; + } + + esp_netif_get_ip_info(s_ap_netif, &(esp_netif_ip_info_t){0}); + esp_netif_ip_info_t ap_ip_info; + esp_netif_get_ip_info(s_ap_netif, &ap_ip_info); + + esp_ip4_addr_t upstream_dns; + const ip_addr_t *dns_addr = dns_getserver(0); + upstream_dns.addr = dns_addr->addr; + + firewall_init(ap_ip_info.ip); + + dns_server_start(ap_ip_info.ip, upstream_dns); + captive_portal_start(); + + s_services_running = true; + if (s_services_mutex) xSemaphoreGive(s_services_mutex); + ESP_LOGI(TAG, "=== TollGate services started ==="); +} + +static void stop_services(void) +{ + if (s_services_mutex) xSemaphoreTake(s_services_mutex, portMAX_DELAY); + if (!s_services_running) { + if (s_services_mutex) xSemaphoreGive(s_services_mutex); + return; + } + + captive_portal_stop(); + dns_server_stop(); + firewall_disable_nat(); + firewall_revoke_all(); + s_services_running = false; + if (s_services_mutex) xSemaphoreGive(s_services_mutex); + ESP_LOGI(TAG, "=== TollGate services stopped ==="); +} + +static void wifi_create_ap_netif(void) +{ + s_ap_netif = esp_netif_create_default_wifi_ap(); + + esp_netif_ip_info_t ip_info = { + .ip.addr = esp_ip4addr_aton(AP_IP_ADDR), + .gw.addr = esp_ip4addr_aton(AP_IP_ADDR), + .netmask.addr = esp_ip4addr_aton(AP_SUBNET), + }; + ESP_ERROR_CHECK(esp_netif_dhcps_stop(s_ap_netif)); + ESP_ERROR_CHECK(esp_netif_set_ip_info(s_ap_netif, &ip_info)); + ESP_ERROR_CHECK(esp_netif_dhcps_start(s_ap_netif)); + + dhcps_offer_t offer_dns = true; + esp_netif_dhcps_option(s_ap_netif, ESP_NETIF_OP_SET, ESP_NETIF_DOMAIN_NAME_SERVER, + &offer_dns, sizeof(offer_dns)); +} + +static void wifi_configure_ap(void) +{ + const tollgate_config_t *cfg = tollgate_config_get(); + wifi_config_t ap_config = {0}; + strncpy((char *)ap_config.ap.ssid, cfg->ap_ssid, sizeof(ap_config.ap.ssid) - 1); + if (strlen(cfg->ap_password) > 0) { + strncpy((char *)ap_config.ap.password, cfg->ap_password, sizeof(ap_config.ap.password) - 1); + ap_config.ap.authmode = WIFI_AUTH_WPA2_PSK; + } else { + ap_config.ap.authmode = WIFI_AUTH_OPEN; + } + ap_config.ap.channel = cfg->ap_channel; + ap_config.ap.max_connection = cfg->ap_max_conn; + ap_config.ap.ssid_hidden = 0; + + ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &ap_config)); + ESP_LOGI(TAG, "AP configured: SSID='%s', channel=%d", cfg->ap_ssid, cfg->ap_channel); +} + +static void wifi_init_sta(void) +{ + s_sta_netif = esp_netif_create_default_wifi_sta(); +} + +void app_main(void) +{ + ESP_LOGI(TAG, "=== TollGate ESP32 Starting ==="); + + esp_err_t ret = nvs_flash_init(); + if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { + ESP_ERROR_CHECK(nvs_flash_erase()); + ret = nvs_flash_init(); + } + ESP_ERROR_CHECK(ret); + + ESP_ERROR_CHECK(tollgate_config_init()); + ESP_ERROR_CHECK(esp_netif_init()); + ESP_ERROR_CHECK(esp_event_loop_create_default()); + + s_wifi_event_group = xEventGroupCreate(); + s_services_mutex = xSemaphoreCreateMutex(); + + wifi_init_sta(); + wifi_create_ap_netif(); + + wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); + ESP_ERROR_CHECK(esp_wifi_init(&cfg)); + + ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, + &wifi_event_handler, NULL, NULL)); + ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, + &ip_event_handler, NULL, NULL)); + ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_LOST_IP, + &ip_event_handler, NULL, NULL)); + + ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_APSTA)); + + wifi_configure_ap(); + + wifi_config_t sta_config; + if (tollgate_config_get_wifi(&sta_config) == ESP_OK) { + ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &sta_config)); + const tollgate_config_t *tcfg = tollgate_config_get(); + ESP_LOGI(TAG, "STA configured for SSID: %s", tcfg->networks[tcfg->current_network].ssid); + } + + ESP_ERROR_CHECK(esp_wifi_start()); + + ESP_LOGI(TAG, "WiFi AP+STA started, waiting for connection..."); +} -- cgit v1.2.3