1 /* Sniffer example.
2    This example code is in the Public Domain (or CC0 licensed, at your option.)
3 
4    Unless required by applicable law or agreed to in writing, this
5    software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
6    CONDITIONS OF ANY KIND, either express or implied.
7 */
8 
9 #include <stdio.h>
10 #include <string.h>
11 #include <stdlib.h>
12 #include "sdkconfig.h"
13 #include "linenoise/linenoise.h"
14 #include "argtable3/argtable3.h"
15 #include "esp_console.h"
16 #include "esp_event.h"
17 #include "esp_vfs_fat.h"
18 #include "esp_wifi.h"
19 #include "esp_err.h"
20 #include "esp_log.h"
21 #if CONFIG_SNIFFER_PCAP_DESTINATION_SD
22 #include "driver/sdmmc_host.h"
23 #include "driver/sdspi_host.h"
24 #include "driver/spi_common.h"
25 #endif
26 #include "nvs_flash.h"
27 #include "sdmmc_cmd.h"
28 #include "cmd_sniffer.h"
29 #include "cmd_pcap.h"
30 #if CONFIG_ETH_USE_SPI_ETHERNET
31 #include "driver/spi_master.h"
32 #endif // CONFIG_ETH_USE_SPI_ETHERNET
33 
34 #if CONFIG_SNIFFER_STORE_HISTORY
35 #define HISTORY_MOUNT_POINT "/data"
36 #define HISTORY_FILE_PATH HISTORY_MOUNT_POINT "/history.txt"
37 #endif
38 
39 #if CONFIG_SNIFFER_SD_SPI_MODE
40 
41 #if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2
42 #define PIN_NUM_MISO 2
43 #define PIN_NUM_MOSI 15
44 #define PIN_NUM_CLK  14
45 #define PIN_NUM_CS   13
46 
47 #elif CONFIG_IDF_TARGET_ESP32C3
48 #define PIN_NUM_MISO 18
49 #define PIN_NUM_MOSI 9
50 #define PIN_NUM_CLK  8
51 #define PIN_NUM_CS   19
52 #endif //CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2
53 
54 #endif  // CONFIG_SNIFFER_SD_SPI_MODE
55 
56 static const char *TAG = "example";
57 
58 #if CONFIG_SNIFFER_STORE_HISTORY
59 /* Initialize filesystem for command history store */
initialize_filesystem(void)60 static void initialize_filesystem(void)
61 {
62     static wl_handle_t wl_handle;
63     const esp_vfs_fat_mount_config_t mount_config = {
64         .max_files = 4,
65         .format_if_mount_failed = true
66     };
67     esp_err_t err = esp_vfs_fat_spiflash_mount(HISTORY_MOUNT_POINT, "storage", &mount_config, &wl_handle);
68     if (err != ESP_OK) {
69         ESP_LOGE(TAG, "Failed to mount FATFS (%s)", esp_err_to_name(err));
70         return;
71     }
72 }
73 #endif
74 
initialize_nvs(void)75 static void initialize_nvs(void)
76 {
77     esp_err_t err = nvs_flash_init();
78     if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
79         ESP_ERROR_CHECK(nvs_flash_erase());
80         err = nvs_flash_init();
81     }
82     ESP_ERROR_CHECK(err);
83 }
84 
85 /* Initialize wifi with tcp/ip adapter */
initialize_wifi(void)86 static void initialize_wifi(void)
87 {
88     wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
89     ESP_ERROR_CHECK(esp_wifi_init(&cfg));
90     ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
91     ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_NULL));
92 }
93 
94 #ifndef CONFIG_SNIFFER_NO_ETHERNET
95 /** Event handler for Ethernet events */
eth_event_handler(void * arg,esp_event_base_t event_base,int32_t event_id,void * event_data)96 static void eth_event_handler(void *arg, esp_event_base_t event_base,
97                               int32_t event_id, void *event_data)
98 {
99     uint8_t mac_addr[6] = {0};
100     /* we can get the ethernet driver handle from event data */
101     esp_eth_handle_t eth_handle = *(esp_eth_handle_t *)event_data;
102 
103     switch (event_id) {
104     case ETHERNET_EVENT_CONNECTED:
105         esp_eth_ioctl(eth_handle, ETH_CMD_G_MAC_ADDR, mac_addr);
106         printf("\n");
107         ESP_LOGI(TAG, "Ethernet Link Up");
108         ESP_LOGI(TAG, "Ethernet HW Addr %02x:%02x:%02x:%02x:%02x:%02x\n",
109                  mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);
110         break;
111     case ETHERNET_EVENT_DISCONNECTED:
112         printf("\n");
113         ESP_LOGI(TAG, "Ethernet Link Down");
114         break;
115     case ETHERNET_EVENT_START:
116         printf("\n");
117         ESP_LOGI(TAG, "Ethernet Started");
118         break;
119     case ETHERNET_EVENT_STOP:
120         printf("\n");
121         ESP_LOGI(TAG, "Ethernet Stopped");
122         break;
123     default:
124         break;
125     }
126 }
127 
initialize_eth(void)128 static void initialize_eth(void)
129 {
130     // Register user defined event handers
131     ESP_ERROR_CHECK(esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, &eth_event_handler, NULL));
132 
133     eth_mac_config_t mac_config = ETH_MAC_DEFAULT_CONFIG();
134     eth_phy_config_t phy_config = ETH_PHY_DEFAULT_CONFIG();
135     phy_config.phy_addr = CONFIG_SNIFFER_ETH_PHY_ADDR;
136     phy_config.reset_gpio_num = CONFIG_SNIFFER_ETH_PHY_RST_GPIO;
137 #if CONFIG_SNIFFER_USE_INTERNAL_ETHERNET
138     mac_config.smi_mdc_gpio_num = CONFIG_SNIFFER_ETH_MDC_GPIO;
139     mac_config.smi_mdio_gpio_num = CONFIG_SNIFFER_ETH_MDIO_GPIO;
140     esp_eth_mac_t *mac = esp_eth_mac_new_esp32(&mac_config);
141 #if CONFIG_SNIFFER_ETH_PHY_IP101
142     esp_eth_phy_t *phy = esp_eth_phy_new_ip101(&phy_config);
143 #elif CONFIG_SNIFFER_ETH_PHY_RTL8201
144     esp_eth_phy_t *phy = esp_eth_phy_new_rtl8201(&phy_config);
145 #elif CONFIG_SNIFFER_ETH_PHY_LAN87XX
146     esp_eth_phy_t *phy = esp_eth_phy_new_lan87xx(&phy_config);
147 #elif CONFIG_SNIFFER_ETH_PHY_DP83848
148     esp_eth_phy_t *phy = esp_eth_phy_new_dp83848(&phy_config);
149 #elif CONFIG_SNIFFER_ETH_PHY_KSZ8041
150     esp_eth_phy_t *phy = esp_eth_phy_new_ksz8041(&phy_config);
151 #elif CONFIG_SNIFFER_ETH_PHY_KSZ8081
152     esp_eth_phy_t *phy = esp_eth_phy_new_ksz8081(&phy_config);
153 #endif
154 #elif CONFIG_ETH_USE_SPI_ETHERNET
155     gpio_install_isr_service(0);
156     spi_device_handle_t spi_handle = NULL;
157     spi_bus_config_t buscfg = {
158         .miso_io_num = CONFIG_SNIFFER_ETH_SPI_MISO_GPIO,
159         .mosi_io_num = CONFIG_SNIFFER_ETH_SPI_MOSI_GPIO,
160         .sclk_io_num = CONFIG_SNIFFER_ETH_SPI_SCLK_GPIO,
161         .quadwp_io_num = -1,
162         .quadhd_io_num = -1,
163     };
164     ESP_ERROR_CHECK(spi_bus_initialize(CONFIG_SNIFFER_ETH_SPI_HOST, &buscfg, SPI_DMA_CH_AUTO));
165 
166 #if CONFIG_SNIFFER_USE_KSZ8851SNL
167     spi_device_interface_config_t devcfg = {
168         .mode = 0,
169         .clock_speed_hz = CONFIG_SNIFFER_ETH_SPI_CLOCK_MHZ * 1000 * 1000,
170         .spics_io_num = CONFIG_SNIFFER_ETH_SPI_CS_GPIO,
171         .queue_size = 20
172     };
173     ESP_ERROR_CHECK(spi_bus_add_device(CONFIG_SNIFFER_ETH_SPI_HOST, &devcfg, &spi_handle));
174     /* KSZ8851SNL ethernet driver is based on spi driver */
175     eth_ksz8851snl_config_t ksz8851snl_config = ETH_KSZ8851SNL_DEFAULT_CONFIG(spi_handle);
176     ksz8851snl_config.int_gpio_num = CONFIG_SNIFFER_ETH_SPI_INT_GPIO;
177     esp_eth_mac_t *mac = esp_eth_mac_new_ksz8851snl(&ksz8851snl_config, &mac_config);
178     esp_eth_phy_t *phy = esp_eth_phy_new_ksz8851snl(&phy_config);
179 #elif CONFIG_SNIFFER_USE_DM9051
180     spi_device_interface_config_t devcfg = {
181         .command_bits = 1,
182         .address_bits = 7,
183         .mode = 0,
184         .clock_speed_hz = CONFIG_SNIFFER_ETH_SPI_CLOCK_MHZ * 1000 * 1000,
185         .spics_io_num = CONFIG_SNIFFER_ETH_SPI_CS_GPIO,
186         .queue_size = 20
187     };
188     ESP_ERROR_CHECK(spi_bus_add_device(CONFIG_SNIFFER_ETH_SPI_HOST, &devcfg, &spi_handle));
189     /* dm9051 ethernet driver is based on spi driver */
190     eth_dm9051_config_t dm9051_config = ETH_DM9051_DEFAULT_CONFIG(spi_handle);
191     dm9051_config.int_gpio_num = CONFIG_SNIFFER_ETH_SPI_INT_GPIO;
192     esp_eth_mac_t *mac = esp_eth_mac_new_dm9051(&dm9051_config, &mac_config);
193     esp_eth_phy_t *phy = esp_eth_phy_new_dm9051(&phy_config);
194 #elif CONFIG_SNIFFER_USE_W5500
195     spi_device_interface_config_t devcfg = {
196         .command_bits = 16, // Actually it's the address phase in W5500 SPI frame
197         .address_bits = 8,  // Actually it's the control phase in W5500 SPI frame
198         .mode = 0,
199         .clock_speed_hz = CONFIG_SNIFFER_ETH_SPI_CLOCK_MHZ * 1000 * 1000,
200         .spics_io_num = CONFIG_SNIFFER_ETH_SPI_CS_GPIO,
201         .queue_size = 20
202     };
203     ESP_ERROR_CHECK(spi_bus_add_device(CONFIG_SNIFFER_ETH_SPI_HOST, &devcfg, &spi_handle));
204     /* w5500 ethernet driver is based on spi driver */
205     eth_w5500_config_t w5500_config = ETH_W5500_DEFAULT_CONFIG(spi_handle);
206     w5500_config.int_gpio_num = CONFIG_SNIFFER_ETH_SPI_INT_GPIO;
207     esp_eth_mac_t *mac = esp_eth_mac_new_w5500(&w5500_config, &mac_config);
208     esp_eth_phy_t *phy = esp_eth_phy_new_w5500(&phy_config);
209 #endif
210 #endif // CONFIG_ETH_USE_SPI_ETHERNET
211     esp_eth_config_t config = ETH_DEFAULT_CONFIG(mac, phy);
212     esp_eth_handle_t eth_handle = NULL;
213     ESP_ERROR_CHECK(esp_eth_driver_install(&config, &eth_handle));
214 #if !CONFIG_SNIFFER_USE_INTERNAL_ETHERNET
215     /* The SPI Ethernet module might doesn't have a burned factory MAC address, we cat to set it manually.
216        02:00:00 is a Locally Administered OUI range so should not be used except when testing on a LAN under your control.
217     */
218     ESP_ERROR_CHECK(esp_eth_ioctl(eth_handle, ETH_CMD_S_MAC_ADDR, (uint8_t[]) {
219         0x02, 0x00, 0x00, 0x12, 0x34, 0x56
220     }));
221 #endif
222     /* start Ethernet driver state machine */
223     ESP_ERROR_CHECK(esp_eth_start(eth_handle));
224 
225     /* Register Ethernet interface to could be used by sniffer */
226     ESP_ERROR_CHECK(sniffer_reg_eth_intf(eth_handle));
227 }
228 #endif // CONFIG_SNIFFER_NO_ETHERNET
229 
230 #if CONFIG_SNIFFER_PCAP_DESTINATION_SD
231 static struct {
232     struct arg_str *device;
233     struct arg_end *end;
234 } mount_args;
235 
236 /** 'mount' command */
mount(int argc,char ** argv)237 static int mount(int argc, char **argv)
238 {
239     esp_err_t ret;
240 
241     int nerrors = arg_parse(argc, argv, (void **)&mount_args);
242     if (nerrors != 0) {
243         arg_print_errors(stderr, mount_args.end, argv[0]);
244         return 1;
245     }
246     /* mount sd card */
247     if (!strncmp(mount_args.device->sval[0], "sd", 2)) {
248         ESP_LOGI(TAG, "Initializing SD card");
249         esp_vfs_fat_sdmmc_mount_config_t mount_config = {
250             .format_if_mount_failed = true,
251             .max_files = 4,
252             .allocation_unit_size = 16 * 1024
253         };
254 
255         // initialize SD card and mount FAT filesystem.
256         sdmmc_card_t *card;
257 
258 #if CONFIG_SNIFFER_SD_SPI_MODE
259         ESP_LOGI(TAG, "Using SPI peripheral");
260         sdmmc_host_t host = SDSPI_HOST_DEFAULT();
261         spi_bus_config_t bus_cfg = {
262             .mosi_io_num = PIN_NUM_MOSI,
263             .miso_io_num = PIN_NUM_MISO,
264             .sclk_io_num = PIN_NUM_CLK,
265             .quadwp_io_num = -1,
266             .quadhd_io_num = -1,
267             .max_transfer_sz = 4000,
268         };
269         ret = spi_bus_initialize(host.slot, &bus_cfg, SPI_DMA_CH_AUTO);
270         if (ret != ESP_OK) {
271             ESP_LOGE(TAG, "Failed to initialize bus.");
272             return 1;
273         }
274 
275         // This initializes the slot without card detect (CD) and write protect (WP) signals.
276         // Modify slot_config.gpio_cd and slot_config.gpio_wp if your board has these signals.
277         sdspi_device_config_t slot_config = SDSPI_DEVICE_CONFIG_DEFAULT();
278         slot_config.gpio_cs = PIN_NUM_CS;
279         slot_config.host_id = host.slot;
280 
281         ret = esp_vfs_fat_sdspi_mount(CONFIG_SNIFFER_MOUNT_POINT, &host, &slot_config, &mount_config, &card);
282 
283 #else
284         ESP_LOGI(TAG, "Using SDMMC peripheral");
285         sdmmc_host_t host = SDMMC_HOST_DEFAULT();
286         sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT();
287 
288         gpio_set_pull_mode(15, GPIO_PULLUP_ONLY); // CMD, needed in 4- and 1-line modes
289         gpio_set_pull_mode(2, GPIO_PULLUP_ONLY);  // D0, needed in 4- and 1-line modes
290         gpio_set_pull_mode(4, GPIO_PULLUP_ONLY);  // D1, needed in 4-line mode only
291         gpio_set_pull_mode(12, GPIO_PULLUP_ONLY); // D2, needed in 4-line mode only
292         gpio_set_pull_mode(13, GPIO_PULLUP_ONLY); // D3, needed in 4- and 1-line modes
293 
294         ret = esp_vfs_fat_sdmmc_mount(CONFIG_SNIFFER_MOUNT_POINT, &host, &slot_config, &mount_config, &card);
295 #endif
296 
297         if (ret != ESP_OK) {
298             if (ret == ESP_FAIL) {
299                 ESP_LOGE(TAG, "Failed to mount filesystem. "
300                          "If you want the card to be formatted, set format_if_mount_failed = true.");
301             } else {
302                 ESP_LOGE(TAG, "Failed to initialize the card (%s). "
303                          "Make sure SD card lines have pull-up resistors in place.",
304                          esp_err_to_name(ret));
305             }
306             return 1;
307         }
308         /* print card info if mount successfully */
309         sdmmc_card_print_info(stdout, card);
310     }
311     return 0;
312 }
313 
register_mount(void)314 static void register_mount(void)
315 {
316     mount_args.device = arg_str1(NULL, NULL, "<sd>", "choose a proper device to mount/unmount");
317     mount_args.end = arg_end(1);
318     const esp_console_cmd_t cmd = {
319         .command = "mount",
320         .help = "mount the filesystem",
321         .hint = NULL,
322         .func = &mount,
323         .argtable = &mount_args
324     };
325     ESP_ERROR_CHECK(esp_console_cmd_register(&cmd));
326 }
327 
unmount(int argc,char ** argv)328 static int unmount(int argc, char **argv)
329 {
330     int nerrors = arg_parse(argc, argv, (void **)&mount_args);
331     if (nerrors != 0) {
332         arg_print_errors(stderr, mount_args.end, argv[0]);
333         return 1;
334     }
335     /* unmount sd card */
336     if (!strncmp(mount_args.device->sval[0], "sd", 2)) {
337         if (esp_vfs_fat_sdmmc_unmount() != ESP_OK) {
338             ESP_LOGE(TAG, "Card unmount failed");
339             return -1;
340         }
341         ESP_LOGI(TAG, "Card unmounted");
342     }
343     return 0;
344 }
345 
register_unmount(void)346 static void register_unmount(void)
347 {
348     mount_args.device = arg_str1(NULL, NULL, "<sd>", "choose a proper device to mount/unmount");
349     mount_args.end = arg_end(1);
350     const esp_console_cmd_t cmd = {
351         .command = "unmount",
352         .help = "unmount the filesystem",
353         .hint = NULL,
354         .func = &unmount,
355         .argtable = &mount_args
356     };
357     ESP_ERROR_CHECK(esp_console_cmd_register(&cmd));
358 }
359 #endif // CONFIG_SNIFFER_PCAP_DESTINATION_SD
360 
app_main(void)361 void app_main(void)
362 {
363     initialize_nvs();
364 
365     /*--- Initialize Network ---*/
366     ESP_ERROR_CHECK(esp_event_loop_create_default());
367     /* Initialize WiFi */
368     initialize_wifi();
369 #ifndef CONFIG_SNIFFER_NO_ETHERNET
370     /* Initialize Ethernet */
371     initialize_eth();
372 #endif
373 
374     /*--- Initialize Console ---*/
375     esp_console_repl_t *repl = NULL;
376     esp_console_repl_config_t repl_config = ESP_CONSOLE_REPL_CONFIG_DEFAULT();
377 #if CONFIG_SNIFFER_STORE_HISTORY
378     initialize_filesystem();
379     repl_config.history_save_path = HISTORY_FILE_PATH;
380 #endif
381     repl_config.prompt = "sniffer>";
382 
383     // install console REPL environment
384 #if CONFIG_ESP_CONSOLE_UART
385     esp_console_dev_uart_config_t uart_config = ESP_CONSOLE_DEV_UART_CONFIG_DEFAULT();
386     ESP_ERROR_CHECK(esp_console_new_repl_uart(&uart_config, &repl_config, &repl));
387 #elif CONFIG_ESP_CONSOLE_USB_CDC
388     esp_console_dev_usb_cdc_config_t cdc_config = ESP_CONSOLE_DEV_CDC_CONFIG_DEFAULT();
389     ESP_ERROR_CHECK(esp_console_new_repl_usb_cdc(&cdc_config, &repl_config, &repl));
390 #elif CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG
391     esp_console_dev_usb_serial_jtag_config_t usbjtag_config = ESP_CONSOLE_DEV_USB_SERIAL_JTAG_CONFIG_DEFAULT();
392     ESP_ERROR_CHECK(esp_console_new_repl_usb_serial_jtag(&usbjtag_config, &repl_config, &repl));
393 #endif
394 
395     /* Register commands */
396 #if CONFIG_SNIFFER_PCAP_DESTINATION_SD
397     register_mount();
398     register_unmount();
399 #endif
400     register_sniffer_cmd();
401     register_pcap_cmd();
402 #if CONFIG_SNIFFER_PCAP_DESTINATION_SD
403     printf("\n =======================================================\n");
404     printf(" |         Steps to sniff network packets              |\n");
405     printf(" |                                                     |\n");
406     printf(" |  1. Enter 'help' to check all commands usage        |\n");
407     printf(" |  2. Enter 'mount <device>' to mount filesystem      |\n");
408     printf(" |  3. Enter 'pcap' to create pcap file                |\n");
409     printf(" |  4. Enter 'sniffer' to start capture packets        |\n");
410     printf(" |  5. Enter 'unmount <device>' to unmount filesystem  |\n");
411     printf(" |                                                     |\n");
412     printf(" =======================================================\n\n");
413 #else
414     printf("\n =======================================================\n");
415     printf(" |         Steps to sniff network packets              |\n");
416     printf(" |                                                     |\n");
417     printf(" |  1. Enter 'help' to check all commands' usage       |\n");
418     printf(" |  2. Enter 'pcap' to create pcap file                |\n");
419     printf(" |  3. Enter 'sniffer' to start capture packets        |\n");
420     printf(" |                                                     |\n");
421     printf(" =======================================================\n\n");
422 #endif
423 
424     // start console REPL
425     ESP_ERROR_CHECK(esp_console_start_repl(repl));
426 }
427