ESP32 – WiFi sniffer

This experimental project shows how to build a simple and inexpensive WiFi packet analyzer (also known as a WiFi sniffer). The heart of this project is WiFi module of ESP32 which is able to work in a promiscusous mode. It means that this clever chip allows IEEE802.11 network packets capturing for further analyzing. Because WiFi module doesn’t implement automated channel switching, additional code has been added in the main loop that switch channels in 500ms intervals.  Presented sniffer requires a callback function that will process all received promiscusous packets. Example callback function displays few basic information like packet type (control packet, management packet, etc.), RSSI or MAC addresses. The full code is on GitHub, click here.

Promiscusous Packet Structure

Data Types

/** 
 * Ref: https://github.com/espressif/esp-idf/blob/master/components/esp32/include/esp_wifi_types.h 
 */
typedef struct {
    signed rssi:8;            /**< signal intensity of packet */
    unsigned rate:5;          /**< data rate */
    unsigned :1;              /**< reserve */
    unsigned sig_mode:2;      /**< 0:is not 11n packet; 1:is 11n packet */
    unsigned :16;             /**< reserve */
    unsigned mcs:7;           /**< if is 11n packet, shows the modulation(range from 0 to 76) */
    unsigned cwb:1;           /**< if is 11n packet, shows if is HT40 packet or not */
    unsigned :16;             /**< reserve */
    unsigned smoothing:1;     /**< reserve */
    unsigned not_sounding:1;  /**< reserve */
    unsigned :1;              /**< reserve */
    unsigned aggregation:1;   /**< Aggregation */
    unsigned stbc:2;          /**< STBC */
    unsigned fec_coding:1;    /**< if is 11n packet, shows if is LDPC packet or not */
    unsigned sgi:1;           /**< SGI */
    unsigned noise_floor:8;   /**< noise floor */
    unsigned ampdu_cnt:8;     /**< ampdu cnt */
    unsigned channel:4;       /**< which channel this packet in */
    unsigned :12;             /**< reserve */
    unsigned timestamp:32;    /**< timestamp */
    unsigned :32;             /**< reserve */
    unsigned :32;             /**< reserve */
    unsigned sig_len:12;      /**< It is really lenth of packet */
    unsigned :12;             /**< reserve */
    unsigned rx_state:8;      /**< rx state */
} wifi_pkt_rx_ctrl_t;

typedef struct {
    wifi_pkt_rx_ctrl_t rx_ctrl;
    uint8_t payload[0];       /**< ieee80211 packet buff, The length of payload is described by sig_len */
} wifi_promiscuous_pkt_t;


/** 
 * Ref: https://github.com/lpodkalicki/blog/blob/master/esp32/016_wifi_sniffer/main/main.c 
 */
typedef struct {
    unsigned frame_ctrl:16;
    unsigned duration_id:16;
    uint8_t addr1[6]; /* receiver address */
    uint8_t addr2[6]; /* sender address */
    uint8_t addr3[6]; /* filtering address */
    unsigned sequence_ctrl:16;
    uint8_t addr4[6]; /* optional */
} wifi_ieee80211_mac_hdr_t;

typedef struct {
    wifi_ieee80211_mac_hdr_t hdr;
    uint8_t payload[0]; /* network data ended with 4 bytes csum (CRC32) */
} wifi_ieee80211_packet_t;

Parts List

  • ESP-WROOM-32 module
  • USB<->TTL converter (3.3.V)
  • Efficient power supply (3.3V)
  • R1 – resistor 560Ω, see LED Resistor Calculator
  • LED1 – basic LED

Circuit Diagram

Firmware

This code is written in C and can be compiled using xtensa-esp32-elf-gcc.  Don’t know how to start  ? Please read about how to compile and upload program into ESP32.

/**
 * Copyright (c) 2017, Łukasz Marcin Podkalicki <lpodkalicki@gmail.com>
 * ESP32/016
 * WiFi Sniffer.
 */

#include "freertos/FreeRTOS.h"
#include "esp_wifi.h"
#include "esp_wifi_types.h"
#include "esp_system.h"
#include "esp_event.h"
#include "esp_event_loop.h"
#include "nvs_flash.h"
#include "driver/gpio.h"

#define    LED_GPIO_PIN                    GPIO_NUM_4
#define    WIFI_CHANNEL_MAX                (13)
#define    WIFI_CHANNEL_SWITCH_INTERVAL    (500)

typedef struct {
    unsigned frame_ctrl:16;
    unsigned duration_id:16;
    uint8_t addr1[6]; /* receiver address */
    uint8_t addr2[6]; /* sender address */
    uint8_t addr3[6]; /* filtering address */
    unsigned sequence_ctrl:16;
    uint8_t addr4[6]; /* optional */
} wifi_ieee80211_mac_hdr_t;

typedef struct {
    wifi_ieee80211_mac_hdr_t hdr;
    uint8_t payload[0]; /* network data ended with 4 bytes csum (CRC32) */
} wifi_ieee80211_packet_t;

static esp_err_t event_handler(void *ctx, system_event_t *event);
static void wifi_sniffer_init(void);
static void wifi_sniffer_set_channel(uint8_t channel);
static const char *wifi_sniffer_packet_type2str(wifi_promiscuous_pkt_type_t type);
static void wifi_sniffer_packet_handler(void *buff, wifi_promiscuous_pkt_type_t type);

void
app_main(void)
{
    uint8_t level = 0, channel = 1;

    /* setup */
    wifi_sniffer_init();
    gpio_set_direction(LED_GPIO_PIN, GPIO_MODE_OUTPUT);

    /* loop */
    while (true) {
        gpio_set_level(LED_GPIO_PIN, level ^= 1);
        vTaskDelay(WIFI_CHANNEL_SWITCH_INTERVAL / portTICK_PERIOD_MS);
        wifi_sniffer_set_channel(channel);
        channel = (channel % WIFI_CHANNEL_MAX) + 1;
    }
}

esp_err_t
event_handler(void *ctx, system_event_t *event)
{
    
    return ESP_OK;
}

void
wifi_sniffer_init(void)
{

    nvs_flash_init();
    tcpip_adapter_init();
    ESP_ERROR_CHECK( esp_event_loop_init(event_handler, NULL) );
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK( esp_wifi_init(&cfg) );
    /* set country EU for channel range [1, 13] */    
    ESP_ERROR_CHECK( esp_wifi_set_country(WIFI_COUNTRY_EU) );         
    ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM) );
    ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_NULL) );
    ESP_ERROR_CHECK( esp_wifi_start() );
    esp_wifi_set_promiscuous(true);
    esp_wifi_set_promiscuous_rx_cb(&wifi_sniffer_packet_handler);
}

void
wifi_sniffer_set_channel(uint8_t channel)
{
    
    esp_wifi_set_channel(channel, WIFI_SECOND_CHAN_NONE);
}

const char *
wifi_sniffer_packet_type2str(wifi_promiscuous_pkt_type_t type)
{
    switch(type) {
    case WIFI_PKT_CTRL: return "CTRL";
    case WIFI_PKT_MGMT: return "MGMT";
    case WIFI_PKT_DATA: return "DATA";
    default:    
    case WIFI_PKT_MISC: return "MISC";
    }
}

void
wifi_sniffer_packet_handler(void* buff, wifi_promiscuous_pkt_type_t type)
{

    if (type != WIFI_PKT_MGMT)
        return;

    const wifi_promiscuous_pkt_t *ppkt = (wifi_promiscuous_pkt_t *)buff;
    const wifi_ieee80211_packet_t *ipkt = (wifi_ieee80211_packet_t *)ppkt->payload;
    const wifi_ieee80211_mac_hdr_t *hdr = &ipkt->hdr;

    printf("PACKET TYPE=%s, CHAN=%02d, RSSI=%02d,"
        " ADDR1=%02x:%02x:%02x:%02x:%02x:%02x,"
        " ADDR2=%02x:%02x:%02x:%02x:%02x:%02x,"
        " ADDR3=%02x:%02x:%02x:%02x:%02x:%02x\n", 
        wifi_sniffer_packet_type2str(type),
        ppkt->rx_ctrl.channel,
        ppkt->rx_ctrl.rssi,
        /* ADDR1 */
        hdr->addr1[0],hdr->addr1[1],hdr->addr1[2],
        hdr->addr1[3],hdr->addr1[4],hdr->addr1[5],
        /* ADDR2 */
        hdr->addr2[0],hdr->addr2[1],hdr->addr2[2],
        hdr->addr2[3],hdr->addr2[4],hdr->addr2[5],
        /* ADDR3 */
        hdr->addr3[0],hdr->addr3[1],hdr->addr3[2],
        hdr->addr3[3],hdr->addr3[4],hdr->addr3[5]
    );
}

17 thoughts on “ESP32 – WiFi sniffer

  1. Where do you set the ssid and the password of the network? I mean, how does the esp32 know, ‘where’ he has to capture the network traffic?

    • You don’t need to set SSID/password after its been turned into promiscuous mode. This mode allows you to capture all packets from the current WiFi channel of ESP32 module.

  2. does this capture the handshake packets as well? i was under the impression the 8266 dropped them and that was a conscious decision on the makers part. I am currently building a sophisticated pen testing rig (hid capture and clone at a distance, 4s lipo, raspi with soft power switch..etc)and would love to throw one of these on if it can d0 hand shakes

  3. Have you actually tried to build this and test it? Doesn’t promiscuous mode require the device to be already connected to a network?

    • Why should promiscuous mode need to be connected to a network? Have you read what promicuous mode is and what is it for?

  4. I tried your code with latest esp-idf (mid August) but it captures only management packets.

    No way to sniff data packets at all!
    Do you know the reason?

    • It captures management packets due to if-condition inside the function. It imply other packets are just dropped. If you remove that condition then it should capture other packets as well.

  5. It works like a charm, but a change needs to be done in order to compile correctly.

    The line
    case WIFI_PKT_CTRL: return “CTRL”;
    shoud be commented or removed, because the type WIFI_PKT_CTRL is not included in esp_wifi_types.h and this kind of packets don’t have any interesting meaning.

    Thanks Łukasz 🙂

    • You’re welcome! 🙂 Thanks for reply on that. Good hint. I need to verify it again as esp-idf is constantly maintained what is so amazing.

  6. Hi Łukasz
    Thanks for this example ..is working like charme 🙂
    as i develop this stuff with eclipse/SLOEBER i needed some minor adaption concerning setup() and loop

    uint8_t level = 0, channel = 1;

    // the setup function runs once when you press reset or power the board
    void setup() {
    // initialize digital pin 13 as an output.
    Serial.begin(115200);
    delay(10);
    wifi_sniffer_init();
    gpio_set_direction(LED_GPIO_PIN, GPIO_MODE_OUTPUT);
    }
    // the loop function runs over and over again forever
    void loop() {
    Serial.print(“huhuhuhu”);
    delay(1000); // wait for a second
    gpio_set_level(LED_GPIO_PIN, level ^= 1);
    vTaskDelay(WIFI_CHANNEL_SWITCH_INTERVAL / portTICK_PERIOD_MS);
    wifi_sniffer_set_channel(channel);
    channel = (channel % WIFI_CHANNEL_MAX) + 1;
    }
    ..instead of your void Main loop
    and i needed the #include for this serial out..

    GREAT base now..:-)
    in my last ESP8266 project i combined the promiscuous mode with station-Mode. the module is sniffing the channels..stop..and transfer this data via REST-API to a webServer..( and MS SQL DB ).
    this all in a loop!
    In my 8266 scatch i additionally sniff the SSID..wondering if ESP32 also will be able to get the SSID!?

    now i will digg deeper into your code and bring it hopefully to fly like ESP8266 (promiscuous + Station ).
    Target is then to additionally SNIFF the BLE ( also in promiscuous??) ..this all together will ( hopefully ) give a quite “complete” signature of moving objects 😉

    greets
    kristina

    • Hi, thanks for sharing the code! I’m sure you can find all visible acesspoints by capturing their prob req/resp packets containing all that info, i.e. SSID/BSSID.
      Ps.: I love this line 🙂 Serial.print(“huhuhuhu”);
      Cheers! L

  7. I’m going to look at this code this weekend.

    Łukasz, I know the Arduino IDE is a C++ compiler – do you know what I’d need to do to get started converting your program to Arduino IDE? I’m guessing I might need to add some .h files, and alter some function calls?

    I’d be happy if I can drop it straight in!

    • Sarah, I’m quite sure you can do that using Arduino IDE and some Arduino libraries able to manage WiFi settings. Arduino IDE uses low-level functions from ESP-IDF project which I’m using directly in my project. What you need is set WiFi mode to WIFI_MODE_NULL (no AP nor STATION), then turn WiFi into promiscusous mode (sniffing mode) and finally register custom handler able to process raw packets. Packet structure should be the same. Good luck!

  8. In file included from F:/esp32/esp-idf/components/esp32/include/esp_system.h:20:0,
    from F:/esp32/esp-idf/components/freertos/include/freertos/portable.h:126,
    from F:/esp32/esp-idf/components/freertos/include/freertos/FreeRTOS.h:105,
    from F:/esp32/blog-master/esp32/016_wifi_sniffer/main/main.c:7:
    F:/esp32/blog-master/esp32/016_wifi_sniffer/main/main.c: In function ‘wifi_sniffer_init’:
    F:/esp32/blog-master/esp32/016_wifi_sniffer/main/main.c:76:40: error: ‘WIFI_COUNTRY_EU’ undeclared (first use in this function)
    ESP_ERROR_CHECK( esp_wifi_set_country(WIFI_COUNTRY_EU) );
    ^
    F:/esp32/esp-idf/components/esp32/include/esp_err.h:72:25: note: in definition of macro ‘ESP_ERROR_CHECK’
    esp_err_t rc = (x); \
    ^
    F:/esp32/blog-master/esp32/016_wifi_sniffer/main/main.c:76:40: note: each undeclared identifier is reported only once for each function it appears in
    ESP_ERROR_CHECK( esp_wifi_set_country(WIFI_COUNTRY_EU) );
    ^
    F:/esp32/esp-idf/components/esp32/include/esp_err.h:72:25: note: in definition of macro ‘ESP_ERROR_CHECK’
    esp_err_t rc = (x); \
    ^
    F:/esp32/blog-master/esp32/016_wifi_sniffer/main/main.c: In function ‘wifi_sniffer_packet_type2str’:
    F:/esp32/blog-master/esp32/016_wifi_sniffer/main/main.c:95:7: error: ‘WIFI_PKT_CTRL’ undeclared (first use in this function)
    case WIFI_PKT_CTRL: return “CTRL”;
    ^
    make[1]: *** [/f/esp32/esp-idf/make/component_wrapper.mk:243: main.o] Error 1
    make: *** [F:/esp32/esp-idf/make/project.mk:435: component-main-build] Error 2

    How to fix this?

    • Hi, looks like the compiler says that you have a few undefined’s. I think you’re using newest version of ESP-IDF where arguments passed to these functions has been changed a little, i.e.:


      /* ref: https://github.com/espressif/esp-idf/blob/3a271a4ae7df8a9049fbbb801feafca5043c31eb/components/esp32/include/esp_wifi_types.h */
      typedef struct {
      char cc[3]; /* country code string */
      uint8_t schan; /* start channel */
      uint8_t nchan; /* total channel number */
      wifi_country_policy_t policy; /* country policy */
      } wifi_country_t;

      /* ref: https://github.com/espressif/esp-idf/blob/79f206be47c3f608615c1de8c491107e6c9194bb/components/esp32/include/esp_wifi.h */
      esp_err_t esp_wifi_set_country(const wifi_country_t *country);

Leave a Comment