WireGuard implementation for ESP32 Arduino

Overview

WireGuard Implementation for ESP32 Arduino

This is an implementation of the WireGuard® for ESP32 Arduino.

Almost all of this code is based on the WireGuard Implementation for lwIP, but some potion of the code is adjusted to build with ESP32 Arduino.

How to use

  1. Include WireGuard.hpp at the early part of the sketch.
#include <WireGuard.hpp>
  1. Define the instance of the WireGuard class at module level.
static WireGuard wg;
  1. Connect to WiFi AP by using WiFi class.
WiFi.begin(ssid, password);
while( !WiFi.isConnected() ) {
    delay(1000);
}
  1. Sync the system time via NTP.
configTime(9 * 60 * 60, 0, "ntp.jst.mfeed.ad.jp", "ntp.nict.jp", "time.google.com");
  1. Start the WireGuard interface.
wg.begin(
    local_ip,           // IP address of the local interface
    private_key,        // Private key of the local interface
    endpoint_address,   // Address of the endpoint peer.
    public_key,         // Public key of the endpoint peer.
    endpoint_port);     // Port pf the endpoint peer.

You can see an example sketch uptime_post.ino, which connects SORACOM Arc WireGuard endpoint and post uptime to SORACOM Harvest via WireGuard connection.

License

The original WireGuard implementation for lwIP is licensed under BSD 3 clause license so the code in this repository also licensed under the same license.

Original license is below:

The code is copyrighted under BSD 3 clause Copyright (c) 2021 Daniel Hope (www.floorsense.nz)

See LICENSE for details

Comments
  • Crash using with ESP32_ETH

    Crash using with ESP32_ETH

    Hi! Thank you for the implementation. It sure looks really promising. I'm trying to initiate a basic communication between esp32 and an android apk for now.

    I'm using ETH implementation by espressif with lan8720 eth board.

    A snippet from my sketch:

    
    void ethEvent(WiFiEvent_t event){
        if( event == SYSTEM_EVENT_ETH_START ){
            ETH.setHostname(config.hostname);
        }else if( event == SYSTEM_EVENT_ETH_GOT_IP ){
            gotIp_MS    = millis();
            gotIP       = true;
            canWireGuardBegin = true;
        }else if( event == SYSTEM_EVENT_ETH_DISCONNECTED ){
            gotIp_MS    = 0;
            gotIP       = false;
        }
    }
    
    inline void startEthernet(){
        Serial.println("Starting ethernet...");
        ETH.begin(
            ETH_PHY_ADDR,
            PIN_PHY_POWER,
            PIN_SMI_MDC,
            PIN_SMI_MDIO,
            ETH_PHY_LAN8720,
            ETH_CLK_MODE
        );
        if( !config.dhcpIsOn )
            {ETH.config(config.ip, config.gw, config.sub, config.dns1, config.dns2);}
        WiFi.onEvent(ethEvent);
    }
    
    void setup(){
        startEthernet();
    }
    
    static WireGuard wg;
    long lastWgPacket = 0;
    boolean canWireGuardBegin   = false;
    boolean isWgConfigured      = false;
    
    static const inline void beginWireGuard(){
        if(canWireGuardBegin){
            canWireGuardBegin = false;
            configTime(9 * 60 * 60, 0, "ntp.jst.mfeed.ad.jp", "ntp.nict.jp", "time.google.com");
            isWgConfigured = wg.begin(
                local_ip,           // IP address of the local interface
                private_key,        // Private key of the local interface
                endpoint_address,   // Address of the endpoint peer.
                public_key,         // Public key of the endpoint peer.
                endpoint_port);     // Port pf the endpoint peer.
    
            Serial.println("isWgConfigured: " + String(isWgConfigured));
            // Sketch is crashing right here, printing: isWgConfigured: 1
        }
    }
    
    void loop(){
        beginWireGuard();
    }
    
    

    Crash LOG:

    isWgConfigured: 1
    Guru Meditation Error: Core  0 panic'ed (LoadProhibited). Exception was unhandled.
    Core 0 register dump:
    PC      : 0x40157cf9  PS      : 0x00060730  A0      : 0x80157f64  A1      : 0x3ffce510  
    A2      : 0x3ffe753c  A3      : 0x3ffe7b70  A4      : 0x3ffe7670  A5      : 0x00000000
    A6      : 0x0000002e  A7      : 0x00000004  A8      : 0x00000000  A9      : 0x3ffe7b73  
    A10     : 0x3ffe7b70  A11     : 0x40089960  A12     : 0x3ffce5fc  A13     : 0x0000003f
    A14     : 0x00002033  A15     : 0x00000091  SAR     : 0x00000018  EXCCAUSE: 0x0000001c  
    EXCVADDR: 0x00000014  LBEG    : 0x4008c8c8  LEND    : 0x4008c8e4  LCOUNT  : 0x00000000
    
    ELF file SHA256: 0000000000000000
    
    Backtrace: 0x40157cf9:0x3ffce510 0x40157f61:0x3ffce550 0x40104da7:0x3ffce570 0x40154fa9:0x3ffce640 
    0x401551b0:0x3ffce660 0x40161320:0x3ffce680 0x4009070a:0x3ffce6b0
      #0  0x40157cf9:0x3ffce510 in udp_sendto_if_src at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/lwip/lwip/src/core/udp.c:720 (discriminator 2)
      #1  0x40157f61:0x3ffce550 in udp_sendto_if at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/lwip/lwip/src/core/udp.c:689
      #2  0x40104da7:0x3ffce570 in wireguardif_peer_output at lib\WireGuard-ESP32-Arduino-main\src/wireguardif.c:912
          (inlined by) wireguard_start_handshake at lib\WireGuard-ESP32-Arduino-main\src/wireguardif.c:635
          (inlined by) wireguardif_tmr at lib\WireGuard-ESP32-Arduino-main\src/wireguardif.c:882       
      #3  0x40154fa9:0x3ffce640 in sys_check_timeouts at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/lwip/lwip/src/core/timeouts.c:381
      #4  0x401551b0:0x3ffce660 in sys_timeouts_mbox_fetch at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/lwip/lwip/src/core/timeouts.c:433
      #5  0x40161320:0x3ffce680 in tcpip_thread at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/lwip/lwip/src/api/tcpip.c:483
      #6  0x4009070a:0x3ffce6b0 in vPortTaskWrapper at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/freertos/port.c:355 (discriminator 1)
    
    Rebooting...
    

    All other standard ethernet communication is working. I have an Async webserver and i can do http requests, websockets and everything else.

    • PlatformIO
    • ESP32-Wrover-E (16mb)
    • Arduino
    bug 
    opened by zekageri 9
  • PlatformIO compile filed with

    PlatformIO compile filed with "xtensa-esp32-elf-as: unrecognized option '-x'"

    Hi, first of all, thanks for your effort! 🚀

    I have a question. We have idea (early WIP) tried to integrate and build project (ESPHome) with your library, but unfortunately, compile filed with xtensa-esp32-elf-as: unrecognized option '-x' error. PlatformIO upgraded and latest version (5.2.0)

    Could you help to find a way to fix this issue? Thanks in advance.

    My config (I tried on fresh project):

    [env:esp-wrover-kit]
    platform = espressif32
    board = esp-wrover-kit
    framework = arduino
    lib_deps = ciniml/WireGuard-ESP32 @ ~0.1.2
    

    Here output of error

    ➜   export LC_ALL=C    
    ➜   platformio run -t upload          
    Processing esp-wrover-kit (platform: espressif32; board: esp-wrover-kit; framework: arduino)
    -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    Verbose mode can be enabled via `-v, --verbose` option
    CONFIGURATION: https://docs.platformio.org/page/boards/espressif32/esp-wrover-kit.html
    PLATFORM: Espressif 32 (3.3.1) > Espressif ESP-WROVER-KIT
    HARDWARE: ESP32 240MHz, 320KB RAM, 4MB Flash
    DEBUG: Current (ftdi) On-board (ftdi) External (esp-prog, iot-bus-jtag, jlink, minimodule, olimex-arm-usb-ocd, olimex-arm-usb-ocd-h, olimex-arm-usb-tiny-h, olimex-jtag-tiny, tumpa)
    PACKAGES: 
     - framework-arduinoespressif32 3.10006.210326 (1.0.6) 
     - tool-esptoolpy 1.30100.210531 (3.1.0) 
     - tool-mkspiffs 2.230.0 (2.30) 
     - toolchain-xtensa32 2.50200.97 (5.2.0)
    LDF: Library Dependency Finder -> http://bit.ly/configure-pio-ldf
    LDF Modes: Finder ~ chain, Compatibility ~ soft
    Found 29 compatible libraries
    Scanning dependencies...
    Dependency Graph
    |-- <WireGuard-ESP32> 0.1.2
    Building in release mode
    Compiling .pio/build/esp-wrover-kit/libca3/WireGuard-ESP32/crypto/cortex/cortex_m0_mpy121666.s.o
    Compiling .pio/build/esp-wrover-kit/libca3/WireGuard-ESP32/crypto/cortex/cortex_m0_reduce25519.s.o
    xtensa-esp32-elf-as: unrecognized option '-x'
    Compiling .pio/build/esp-wrover-kit/libca3/WireGuard-ESP32/crypto/cortex/mul.s.o
    xtensa-esp32-elf-as: unrecognized option '-x'
    xtensa-esp32-elf-as: unrecognized option '-x'
    *** [.pio/build/esp-wrover-kit/libca3/WireGuard-ESP32/crypto/cortex/cortex_m0_mpy121666.s.o] Error 1
    Compiling .pio/build/esp-wrover-kit/libca3/WireGuard-ESP32/crypto/cortex/sqr.s.o
    *** [.pio/build/esp-wrover-kit/libca3/WireGuard-ESP32/crypto/cortex/mul.s.o] Error 1
    *** [.pio/build/esp-wrover-kit/libca3/WireGuard-ESP32/crypto/cortex/cortex_m0_reduce25519.s.o] Error 1
    xtensa-esp32-elf-as: unrecognized option '-x'
    *** [.pio/build/esp-wrover-kit/libca3/WireGuard-ESP32/crypto/cortex/sqr.s.o] Error 1
    ============================================================================== [FAILED] Took 0.83 seconds ==============================================================================
    
    
    opened by mrkeuz 5
  • WireGuard-ESP32-Arduino works on an Inkplate!

    WireGuard-ESP32-Arduino works on an Inkplate!

    Not an issue, per-se, but rather a note to say that this library works flawlessly (for my needs) on an Inkplate 10. Thank you!

    Arduino gives the following warning though:

    WARNING: library WireGuard-ESP32 claims to run on esp32 architecture(s) and may be incompatible with your current board which runs on Inkplate architecture(s)
    

    However, I have found it to work fine.

    Is there any reason in the code that this should not be the case? Are there any ESP32 specific things that might not work in the Inkplate harness? I'd take a look through the code, but don't really have time at the moment to learn its inner workings.

    If not, can I suggest adding Inkplate to the list of supported architectures?

    opened by rspencer01 3
  • Config connects on any other device, except on ESP32

    Config connects on any other device, except on ESP32

    I'm looking for a couple of days now what is wrong with the setup. Wireguard is running on my pfSense and i have created a peer for my ESP32. The config works on any other device i'm trying, but if i use it on a ESP32 it doesn't connect.

    I'm using the example-code, changed the keys and won't see a handshake in my pfSense.

    opened by KoenHaemels 1
  • Trying to port in esp8266  handshake return -8 ERR_USE

    Trying to port in esp8266 handshake return -8 ERR_USE

    Hi thank you for this wonderful library it works perfectly in esp23 from arduino ide but not in esp8266, Maybe you can give me any insights about the error in the handshake where it returns err_t -8 ERR_USE or Address in use, I have managed to overcome this by using the original lwip-wireguard implementation ping works fine but when i try to curl to the esp8266 error comes out Failed to connect to 10.1.0.4 port 80: Connection timed out, the esp8266 seems to receive the packets i can see it on the serial monitor but failed to respond back, I thought this might be some issues of NAT I tried your implementation of ->underlying_netif adn udp_sendto_if but handshake fails saying -8 ERR_USE or Address in use. Thank you, My implementation is a fork of your library with minor changes hope I can make this work soon on esp8266. Here are some changes to make it compile in esp8266.

    //in wireguardif.c wireguardif_init
    #ifdef ESP8266
      underlying_netif = eagle_lwip_getif(STATION_IF);
    #else
      tcpip_adapter_get_netif(TCPIP_ADAPTER_IF_STA, &underlying_netif);
    #endif
    

    Using hydrogen x22519.h to prevent crashing esp8266 and replacing it in crypto.h moving all crypto files to root removing all ESP_LOG or just doing #define ESP_LOGI(...) printf(VA_ARGS) ESP_LOGV(...) printf(VA_ARGS) etc uncommenting esp32 includes thats isnt compatible with esp8266

    opened by rjjrbatarao 1
  • The device with esphome.io firmware reboots approximately every 10 minutes

    The device with esphome.io firmware reboots approximately every 10 minutes

    Hi, i use library with esphome firmware on ESP32 nodemcu 38 pin board (https://github.com/esphome/feature-requests/issues/1444#issuecomment-966295758) everything is great, but controller reboots approximately every 10 minutes. I found the error on ESP log and here is it:

    [21:28:17][D][sntp:075]: Synchronized time: 2021-12-19 21:28:17
    [21:28:17][W][MyModule:020]: _________________________________________
    [21:28:17][W][MyModule:021]: START wirenguard
    [21:28:17][W][MyModule:023]: END wirenguard
    [21:28:17][W][MyModule:024]: _________________________________________
    [21:28:27]Guru Meditation Error: Core  0 panic'ed (LoadProhibited). Exception was unhandled.
    [21:28:27]Core 0 register dump:
    [21:28:27]PC      : 0x400e1177  PS      : 0x00060830  A0      : 0x800e1320  A1      : 0x3ffb5680  
    WARNING Decoded 0x400e1177: wireguardif_peer_output at /data/my_awesome_controller_two/.piolibdeps/my_awesome_controller_two/WireGuard-ESP32/src/wireguardif.c:912
     (inlined by) wireguardif_output_to_peer at /data/my_awesome_controller_two/.piolibdeps/my_awesome_controller_two/WireGuard-ESP32/src/wireguardif.c:162
    [21:28:27]A2      : 0x00000000  A3      : 0x3ffc1970  A4      : 0x3ffd4c34  A5      : 0x3ffd4d24  
    [21:28:27]A6      : 0x3ffd5a34  A7      : 0x00000000  A8      : 0x800e116c  A9      : 0x3ffb5650  
    [21:28:27]A10     : 0x3ffd5aa8  A11     : 0x3ffd5aa8  A12     : 0x3ffd4c50  A13     : 0x0000ca6c  
    [21:28:28]A14     : 0xfffffffc  A15     : 0x00000002  SAR     : 0x00000019  EXCCAUSE: 0x0000001c  
    [21:28:28]EXCVADDR: 0x00000008  LBEG    : 0x400e3e4a  LEND    : 0x400e3e5a  LCOUNT  : 0x00000000  
    [21:28:28]
    [21:28:28]ELF file SHA256: 0000000000000000
    [21:28:28]
    [21:28:28]Backtrace: 0x400e1177:0x3ffb5680 0x400e131d:0x3ffb56b0 0x40139e65:0x3ffb5780 0x4013a06c:0x3ffb57a0 0x4013462c:0x3ffb57c0 0x40089dca:0x3ffb57f0
    WARNING Found stack trace! Trying to decode it
    WARNING Decoded 0x400e1177: wireguardif_peer_output at /data/my_awesome_controller_two/.piolibdeps/my_awesome_controller_two/WireGuard-ESP32/src/wireguardif.c:912
     (inlined by) wireguardif_output_to_peer at /data/my_awesome_controller_two/.piolibdeps/my_awesome_controller_two/WireGuard-ESP32/src/wireguardif.c:162
    WARNING Decoded 0x400e131d: wireguardif_send_keepalive at /data/my_awesome_controller_two/.piolibdeps/my_awesome_controller_two/WireGuard-ESP32/src/wireguardif.c:912
     (inlined by) wireguardif_tmr at /data/my_awesome_controller_two/.piolibdeps/my_awesome_controller_two/WireGuard-ESP32/src/wireguardif.c:879
    WARNING Decoded 0x40139e65: sys_check_timeouts at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/lwip/lwip/src/core/timeouts.c:381
    WARNING Decoded 0x4013a06c: sys_timeouts_mbox_fetch at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/lwip/lwip/src/core/timeouts.c:433
    WARNING Decoded 0x4013462c: tcpip_thread at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/lwip/lwip/src/api/tcpip.c:483
    WARNING Decoded 0x40089dca: vPortTaskWrapper at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/freertos/port.c:355 (discriminator 1)
    [21:28:28]
    [21:28:28]Rebooting...
    

    All recommendations like disabling logging do not help, I have consistently tried disabling everything else, the problem is in WireGuard. One more thing. I think this is due to the period of sntp time synchronization, perhaps at this moment the initialization is called again and crash "[21:28:17][D][sntp:075]: Synchronized time: 2021-12-19 21:28:17"

    opened by vsurkov 1
  • Exclude platform-specific asm files

    Exclude platform-specific asm files

    Exclude unused platform-specific (seems for cortex cores) files after #2. Needed to fix PlatformIO builds when WireGuard-ESP32 lib included as dependency.

    opened by mrkeuz 1
  • W5500 + EthernetWebServer

    W5500 + EthernetWebServer

    Hello to all Hardware: ESP 32 + W 5500 Module Software: PlatformIO + Visual Studio Code Libraries used: WireGuard-ESP32.h + EthernetWebServer.h You can see the above libraries in the following links on github. https://github.com/ciniml/WireGuard-ESP32-Arduino https://github.com/khoih-prog/EthernetWebServer I can connect to Wireguard VPN Server using WiFi connection and WireGuard-ESP32.h library and everything works fine and sending and receiving data is fine. When using the EthernetWebServer.h library, the device is connected to the Internet and can be seen and pinged in the Local network, and even when connected to the Wireguard VPN Server, the function wg.is_initialized() returns the value 1, but in sending and receiving data There is a problem. Where do you think the problems are?

    opened by MahdiBabaie 0
  • Difficulties with UDP Server (AsyncUDP / WiFiUDP)

    Difficulties with UDP Server (AsyncUDP / WiFiUDP)

    Hello,

    really nice project, i am playing all day with the library and testing different setups. So far i didn't had any issues as TCP or UDP client.

    But when i tested WiFiUDP and AsyncUDP as server, i run into weird problems. This is the output when i use AsyncUDP and listen

    Sending packet to normal IP as Unicast

    UDP Packet Type: Unicast, From: 192.168.123.133:1234, To: 192.168.123.123:1234, Length: 24, Data: hello world, hello world
    UDP Packet Type: Unicast, From: 192.168.123.133:1234, To: 192.168.123.123:1234, Length: 24, Data: hello world, hello world
    UDP Packet Type: Unicast, From: 192.168.123.133:1234, To: 192.168.123.123:1234, Length: 24, Data: hello world, hello world
    UDP Packet Type: Unicast, From: 192.168.123.133:1234, To: 192.168.123.123:1234, Length: 24, Data: hello world, hello world
    UDP Packet Type: Unicast, From: 192.168.123.133:1234, To: 192.168.123.123:1234, Length: 24, Data: hello world, hello world
    UDP Packet Type: Unicast, From: 192.168.123.133:1234, To: 192.168.123.123:1234, Length: 24, Data: hello world, hello world
    UDP Packet Type: Unicast, From: 192.168.123.133:1234, To: 192.168.123.123:1234, Length: 24, Data: hello world, hello world
    UDP Packet Type: Unicast, From: 192.168.123.133:1234, To: 192.168.123.123:1234, Length: 24, Data: hello world, hello world
    UDP Packet Type: Unicast, From: 192.168.123.133:1234, To: 192.168.123.123:1234, Length: 24, Data: hello world, hello world
            [ 14621][V][wireguardif.c:559] wireguardif_network_rx(): [[WireGuard] ] network_rx: 857ba8c0:51820
            [ 14622][I][wireguardif.c:564] wireguardif_network_rx(): [WireGuard] HANDSHAKE_INITIATION: 857ba8c0:51820
    UDP Packet Type: Unicast, From: 192.168.123.133:1234, To: 192.168.123.123:1234, Length: 24, Data: hello world, hello world
    UDP Packet Type: Unicast, From: 192.168.123.133:1234, To: 192.168.123.123:1234, Length: 24, Data: hello world, hello world
            [ 14806][V][wireguardif.c:559] wireguardif_network_rx(): [[WireGuard] ] network_rx: 857ba8c0:51820
            [ 14807][V][wireguardif.c:609] wireguardif_network_rx(): [[WireGuard] ] TRANSPORT_DATA: 857ba8c0:51820
    UDP Packet Type: Unicast, From: 192.168.123.133:1234, To: 192.168.123.123:1234, Length: 24, Data: hello world, hello world
            [ 15187][V][wireguardif.c:136] wireguardif_output_to_peer(): [WireGuard] preparing transport data...
    UDP Packet Type: Unicast, From: 192.168.123.133:1234, To: 192.168.123.123:1234, Length: 24, Data: hello world, hello world
    UDP Packet Type: Unicast, From: 192.168.123.133:1234, To: 192.168.123.123:1234, Length: 24, Data: hello world, hello world
    UDP Packet Type: Unicast, From: 192.168.123.133:1234, To: 192.168.123.123:1234, Length: 24, Data: hello world, hello world
    UDP Packet Type: Unicast, From: 192.168.123.133:1234, To: 192.168.123.123:1234, Length: 24, Data: hello world, hello world
            [ 16965][V][wireguardif.c:136] wireguardif_output_to_peer(): [WireGuard] preparing transport data...
            [ 27187][V][wireguardif.c:136] wireguardif_output_to_peer(): [WireGuard] preparing transport data...
    

    Sending packet to normal IP as Broadcast

    UDP Packet Type: Broadcast, From: 192.168.123.133:1234, To: 255.255.255.255:1234, Length: 24, Data: hello world, hello world
    UDP Packet Type: Broadcast, From: 192.168.123.133:1234, To: 255.255.255.255:1234, Length: 24, Data: hello world, hello world
    UDP Packet Type: Broadcast, From: 192.168.123.133:1234, To: 255.255.255.255:1234, Length: 24, Data: hello world, hello world
    UDP Packet Type: Broadcast, From: 192.168.123.133:1234, To: 255.255.255.255:1234, Length: 24, Data: hello world, hello world
    UDP Packet Type: Broadcast, From: 192.168.123.133:1234, To: 255.255.255.255:1234, Length: 24, Data: hello world, hello world
    UDP Packet Type: Broadcast, From: 192.168.123.133:1234, To: 255.255.255.255:1234, Length: 24, Data: hello world, hello world
    UDP Packet Type: Broadcast, From: 192.168.123.133:1234, To: 255.255.255.255:1234, Length: 24, Data: hello world, hello world
    UDP Packet Type: Broadcast, From: 192.168.123.133:1234, To: 255.255.255.255:1234, Length: 24, Data: hello world, hello world
            [ 32036][V][wireguardif.c:136] wireguardif_output_to_peer(): [WireGuard] preparing transport data...
            [ 40220][V][wireguardif.c:559] wireguardif_network_rx(): [[WireGuard] ] network_rx: 857ba8c0:51820
            [ 40221][V][wireguardif.c:609] wireguardif_network_rx(): [[WireGuard] ] TRANSPORT_DATA: 857ba8c0:51820
    

    Sending same packet to WireGuard IP

    Guru Meditation Error: Core  0 panic'ed (LoadProhibited). Exception was unhandled.
    
    Core  0 register dump:
    PC      : 0x400896b3  PS      : 0x00060330  A0      : 0x800e7ef5  A1      : 0x3ffcd790  
    A2      : 0x00000000  A3      : 0x3ffb5ac8  A4      : 0x00000000  A5      : 0x3ffc46a8  
    A6      : 0x00060f20  A7      : 0x00000001  A8      : 0x800e7d36  A9      : 0x3ffcd740  
    A10     : 0x00000001  A11     : 0x3ffb5660  A12     : 0x3ffb5614  A13     : 0x00000000  
    A14     : 0x3ffb5660  A15     : 0x00000000  SAR     : 0x00000010  EXCCAUSE: 0x0000001c  
    EXCVADDR: 0x00000000  LBEG    : 0x40089701  LEND    : 0x40089711  LCOUNT  : 0xfffffff3  
    
    
    Backtrace:0x400896b0:0x3ffcd7900x400e7ef2:0x3ffcd7a0 0x400e7b15:0x3ffcd7c0 0x400e7b68:0x3ffcd7e0 0x400e7bc6:0x3ffcd800 0x400d82a2:0x3ffcd820 0x400d85d3:0x3ffcd850 0x400d860b:0x3ffcd8e0 0x400d8640:0x3ffcd900 
    
      #0  0x400896b0:0x3ffcd790 in strcmp at /builds/idf/crosstool-NG/.build/xtensa-esp32-elf/src/newlib/newlib/libc/machine/xtensa/strcmp.S:467
      #1  0x400e7ef2:0x3ffcd7a0 in esp_netif_get_handle_from_ifkey at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/esp_netif/esp_netif_objects.c:182
      #2  0x400e7b15:0x3ffcd7c0 in netif_from_if at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/tcpip_adapter/tcpip_adapter_compat.c:76
      #3  0x400e7b68:0x3ffcd7e0 in netif_from_if at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/tcpip_adapter/tcpip_adapter_compat.c:74
      #4  0x400e7bc6:0x3ffcd800 in tcpip_adapter_get_netif at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/tcpip_adapter/tcpip_adapter_compat.c:226
      #5  0x400d82a2:0x3ffcd820 in AsyncUDPPacket::AsyncUDPPacket(AsyncUDP*, pbuf*, ip_addr const*, unsigned short, netif*) at /home/user/.platformio/packages/framework-arduinoespressif32/libraries/AsyncUDP/src/AsyncUDP.cpp:334
      #6  0x400d85d3:0x3ffcd850 in AsyncUDP::_recv(udp_pcb*, pbuf*, ip_addr const*, unsigned short, netif*) at /home/user/.platformio/packages/framework-arduinoespressif32/libraries/AsyncUDP/src/AsyncUDP.cpp:700
      #7  0x400d860b:0x3ffcd8e0 in AsyncUDP::_s_recv(void*, udp_pcb*, pbuf*, ip_addr const*, unsigned short, netif*) at /home/user/.platformio/packages/framework-arduinoespressif32/libraries/AsyncUDP/src/AsyncUDP.cpp:709
      #8  0x400d8640:0x3ffcd900 in _udp_task(void*) at /home/user/.platformio/packages/framework-arduinoespressif32/libraries/AsyncUDP/src/AsyncUDP.cpp:137
    
    ELF file SHA256: 0000000000000000
    
    Rebooting...
    ets Jun  8 2016 00:22:57
    
    rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
    

    This is the sourcecode im using

    #include <Arduino.h>
    #include <WiFi.h>
    // #include <WiFiUdp.h>
    #include <WireGuard-ESP32.h>
    #include <AsyncUDP.h>
    
    AsyncUDP udp;
    IPAddress local_ip(172, 16, 23, 2);
    
    char packetBuffer[24];  
    char ssid[] = "SSID";
    char password[] = "PASSWORD";
    
    char private_key[] = "PRIVATE_KEY";
    char public_key[] = "PUBLIC_KEY";
    char endpoint_address[] = "192.168.123.133";
    int endpoint_port = 51820;
    
    static WireGuard wg;
    
    void setup() {
      Serial.begin(115200);
      Serial.println("Connecting to the AP...");
      WiFi.begin(ssid, password);
      while (!WiFi.isConnected()) {
        delay(100);
      }
    
      Serial.println(WiFi.localIP());
      Serial.println("Adjusting system time...");
      configTime(9 * 60 * 60, 0, "ntp.jst.mfeed.ad.jp", "ntp.nict.jp", "time.google.com");
    
      Serial.print("Connected. Initializing WireGuard... ");
      if (wg.begin(local_ip, private_key, endpoint_address, public_key, endpoint_port)) {
        Serial.println("OK");
      } else {
        Serial.println("FAIL");
      }
     
      if (udp.listen(1234)) {
        Serial.print("UDP Listening on IP: ");
        Serial.println(WiFi.localIP());
        
        udp.onPacket([](AsyncUDPPacket packet) {
          Serial.print("UDP Packet Type: ");
          Serial.print(packet.isBroadcast() ? "Broadcast" : packet.isMulticast() ? "Multicast" : "Unicast");
          Serial.print(", From: ");
          Serial.print(packet.remoteIP());
          Serial.print(":");
          Serial.print(packet.remotePort());
          Serial.print(", To: ");
          Serial.print(packet.localIP());
          Serial.print(":");
          Serial.print(packet.localPort());
          Serial.print(", Length: ");
          Serial.print(packet.length());
          Serial.print(", Data: ");
          Serial.write(packet.data(), packet.length());
          Serial.println();
    
          packet.printf("millis %lu", millis());
        });
      }
    
    }
    
    void loop() {
      delay(10);
    }
    

    and this is the working sourcecode with WiFiUDP. The only issue is that many times the server is not responsive, until a new Handshake is exchanged.

    #include <Arduino.h>
    #include <WiFi.h>
    #include <WiFiUdp.h>
    #include <WireGuard-ESP32.h>
    
    WiFiUDP udp;
    IPAddress local_ip(172, 16, 23, 2);
    
    char packetBuffer[24];  
    char ssid[] = "SSID";
    char password[] = "PASSWORD";
    
    char private_key[] = "PRIVATE_KEY";
    char public_key[] = "PUBLIC_KEY";
    char endpoint_address[] = "192.168.123.133";
    int endpoint_port = 51820;
    
    static WireGuard wg;
    
    void setup() {
      Serial.begin(115200);
      Serial.println("Connecting to the AP...");
      WiFi.begin(ssid, password);
      while (!WiFi.isConnected()) {
        delay(100);
      }
    
      Serial.println(WiFi.localIP());
      Serial.println("Adjusting system time...");
      configTime(9 * 60 * 60, 0, "ntp.jst.mfeed.ad.jp", "ntp.nict.jp", "time.google.com");
    
      Serial.print("Connected. Initializing WireGuard... ");
      if (wg.begin(local_ip, private_key, endpoint_address, public_key, endpoint_port)) {
        Serial.println("OK");
      } else {
        Serial.println("FAIL");
      }
     
      udp.begin(1234);
    }
    
    void loop() {
      int packetSize = udp.parsePacket();
    
      if (packetSize) {
        if(packetSize >= 25){
          Serial.println("Packet size too big!");
          udp.flush(); // without this line, sketch stop working on wireguard IP but still works with normal IP
          return;
        } 
        
        Serial.print(F("Packet Size: "));
        Serial.print(packetSize);
        Serial.print(F(" Port: "));
        Serial.print(udp.remotePort());
        Serial.print(F(" Data: "));
        udp.read(packetBuffer, 24);
    
        for (int i = 0; i < sizeof(packetBuffer); i++) {
          if (packetBuffer[i] < 16) {
            Serial.print(F("0"));
          }
          Serial.print(packetBuffer[i], HEX);
          Serial.print(F(" "));
        }
        Serial.println();
    
        udp.beginPacket(udp.remoteIP(), udp.remotePort());
        udp.printf("millis %lu", millis());
        udp.endPacket();
        
      }
    
      delay(10);
    }
    
    opened by tkndrm 0
  • Cannot connect to wireguard server by following readme instructions

    Cannot connect to wireguard server by following readme instructions

    Hi,

    I'm working on a project where I have an esp32 as a prometheus endpoint serving the data of a sensor, and in the long term setup, the raspberry pi containing the prometheus and grafana containers will be in a separate network as the esp, both behind a NAT. I was about to install a raspberry pi zero w as a sort of wireguard gateway, I found this library.

    I don't get an error when trying to connect to the wireguard server, but I can't access the esp neither from the wireguard server, nor from a client connected to the same wireguard server, but even with it connected to the wireguard server, I can still access the endpoint via the local IP of the esp. When connected to wireguard, I don't think the esp can access anything via the internet, as it can't sync the time via ntp after connecting to wireguard. Other clients under the same server work properly. I've tried deleting and creating another client on the server, just in case, but that doesn't work either. The following code is what I've uploaded to the esp

    #include <OneWire.h>  // https://www.pjrc.com/teensy/td_libs_OneWire.html
    #include <DallasTemperature.h>  // https://github.com/milesburton/Arduino-Temperature-Control-Library
    #include <WiFi.h>
    #include <WireGuard-ESP32.h>  // https://github.com/ciniml/WireGuard-ESP32-Arduino
    #include "time.h"
    
    const int oneWirePin = 5; // DS18B20
    OneWire oneWireBus(oneWirePin);
    DallasTemperature t(&oneWireBus);
    
    /* WIFI credentials */
    //const char* ssid = "ssid";  // wifi ssid
    //const char* password = "pass";  // wifi password
    
    /* Server timeout */
    unsigned long currentTime = millis();
    unsigned long previousTime = 0;
    const long timeoutTime = 2000;
    
    /* Wiregard */
    char private_key[] = "private-key";
    IPAddress local_ip(10,7,0,3);
    char public_key[] = "public-key";
    char endpoint_address[] = "vpn-server";
    int endpoint_port = 51820;
    static WireGuard wg;
    
    /* WiFi server */
    WiFiServer server(80);  // Create a server on port 80
    String header;  // Variable to store the header
    
    /* Be able to read the ESPs internal temperature sensor */
    #ifdef __cplusplus
      extern "C" {
    #endif
    
    uint8_t temprature_sens_read();
    
    #ifdef __cplusplus
      }
    #endif
    
    
    /* Get the metrics and format them according to prometheus */
    String getMetrics() {
      String p = "";
      float temp = 0;
    
      float temperature = ((temprature_sens_read() - 32) / 1.8);  // Internal temperature
    
      t.requestTemperatures();  // Get the DS18B20s temperature
      temp = t.getTempCByIndex(0);  // and store it in a variable
    
      setMetric(&p, "esp32_uptime", String(millis()));          // ESP uptime
      setMetric(&p, "esp32_wifi_rssi", String(WiFi.RSSI()));    // WiFi RSSI
      setMetric(&p, "esp32_temperature", String(temperature));  // Internal temperature
      setMetric(&p, "ds18b20_temperature", String(temp));       // DS18B20
    
      return p; // Return an string with all the metrics
    }
    
    /* Create a string containing a metric formated according to prometheus */
    void setMetric(String *p, String metric, String value) {
      *p += "# " + metric + "\n";
      *p += "# TYPE " + metric + " gauge\n";
      *p += "" + metric + " ";
      *p += value;
      *p += "\n";
    }
    
    void setup() {
      Serial.begin(115200); // Serial port
      t.begin();  // DS18B20
      WiFi.begin(ssid, password); // WiFi
    
      /* Wait until wifi has connected */
      while (WiFi.status() != WL_CONNECTED) delay(500);
    
      /* When connected start the server and print the IP */
      Serial.println(WiFi.localIP());
      server.begin();
    
      /* Sync the time via NTP and print it */
      configTime(3600, 3600, "pool.ntp.org");
      struct tm timeinfo;
      if(!getLocalTime(&timeinfo)) Serial.println("Failed to get the time");  // If unable to get the time, print an error
      Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S"); // Otherwise print the time in the format: Weekday, Day Month Year Hour:Minute:Second
    
      /* Also connect to the wireguard VPN */
      Serial.println("Starting WG");
      if(!wg.begin(local_ip, private_key, endpoint_address, public_key, endpoint_port)) Serial.println("Failed to start WG");
    }
    
    void printLocalTime(){
      struct tm timeinfo;
      if(!getLocalTime(&timeinfo)){
        Serial.println("Failed to obtain time");
        return;
      }
      Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
    }
    
    void loop() {
      WiFiClient client = server.available(); // WiFi server is listening
    
      /* When a client connects */
      if (client) {
        currentTime = millis();       // Save current time
        previousTime = currentTime;   // Save lasts connection time
        Serial.println("Client");
        /*struct tm timeinfo;
        Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");   // Print the current time*/
        printLocalTime();
        String currentLine = "";
        /* While the client doesn't go over the timeout time */
        while (client.connected() && currentTime - previousTime <= timeoutTime) {
          currentTime = millis();
          /* If the client is listening */
          if (client.available()) {
            char c = client.read(); // Save the received information
            Serial.write(c);        // And print it
            header += c;
            if (c == '\n') {                    // When an end of line is received
              if (currentLine.length() == 0) {  // And the next line is blank
                /* Send the http header */
                client.println("HTTP/1.1 200 OK");
                client.println("Content-type:text/html");
                client.println("Connection: close");
                client.println();
              }
              client.print(getMetrics()); // Send the metrics
              break;  // Break the loop
            }
          }
        }
        header = "";
        client.stop();  // Disconnect the client
        Serial.println("Disconnected"); // Say so on the serial port
        Serial.println(currentTime - previousTime);
        Serial.println("");
      }
    }
    

    The expected behaviour is: The esp connects to the specified WiFi, and then to the wireguard server, so now, the prometheus container, that is on a docker host in a separate network, but connected to the same vpn, can access the remote esp and save the data to be represented in grafana.

    Thanks

    opened by delthia 0
  • Resolve

    Resolve "implicit declaration of function 'handshake_destroy'" error …

    …in wireguardif.c by

    Microsoft Intellisense reports this error in VSC + Platformio: implicit declaration of function 'handshake_destroy'; did you mean 'keypair_destroy'? [-Wimplicit-function-declaration]

    opened by volcini 0
Releases(0.1.5)
  • 0.1.5(Dec 10, 2021)

    end() function is added to the WireGuard class to shutdown the WireGuard interface.

    After shutting down the WireGuard interface, all communication is routed to the previous default interface, which is used as the underlying interface of the WireGuard interface.

    Source code(tar.gz)
    Source code(zip)
  • 0.1.4(Nov 4, 2021)

  • 0.1.3(Oct 3, 2021)

    Merged two PRs:

    • The handshake must also be destroyed during a timer reset. (https://github.com/ciniml/WireGuard-ESP32-Arduino/pull/1)
    • Exclude platform-specific asm files (https://github.com/ciniml/WireGuard-ESP32-Arduino/pull/3)

    From this release, a project which uses this library can be compiled with Platform IO Arduino backend.

    @mrkeuz @ErikDoell Thanks for contribution!

    Source code(tar.gz)
    Source code(zip)
  • 0.1.2(Aug 5, 2021)

  • 0.1.0(Jul 18, 2021)

Owner
Kenta IDA
Kenta IDA
WireGuard Implementation for lwIP

WireGuard Implementation for lwIP This project is a C implementation of the WireGuard® protocol intended to be used with the lwIP IP stack Motivation

Daniel 121 Dec 31, 2022
High performance in-kernel WireGuard implementation for Windows

WireGuard for the NT Kernel High performance in-kernel WireGuard implementation for Windows WireGuardNT is an implementation of WireGuard, for the NT

WireGuard 60 Dec 2, 2022
This is a kernel module for FreeBSD to support WireGuard

WireGuard for FreeBSD This is a kernel module for FreeBSD to support WireGuard. It is being developed here before its eventual submission to FreeBSD 1

WireGuard 38 Jan 4, 2023
Generate Vanity Public Keys for WireGuard.

wgmine Generate Vanity Public Keys for WireGuard You know what opening a wireguard config and finding out comments have been stripped feels like. You

Alessandro Romani 22 Oct 22, 2022
an esp32 based minecraft server!

esp32-minecraft-server this is an open source implementation of the minecraft server to be run on a esp32. prerequisites esp32 pc with platformio inst

Nik 38 Dec 17, 2022
Asynchronous SSL TCP Library for ESP32.

Asynchronous SSL TCP Library for ESP32. This library is the base for future and more advanced Async SSL libraries, such as AsyncSSLWebServer, AsyncHTTPSRequest

Khoi Hoang 12 Dec 29, 2022
Use an esp32 as gateway for the Eqiva Bluetooth smart lock to integrate it in Home Assistant as MQTT lock

esp32-keyble-homeassistant Use an esp32 as gateway for the Eqiva Bluetooth smart lock to integrate it in Home Assistant as MQTT lock Based on the grea

null 8 Nov 22, 2022
Update ESP32 firmware over WiFi from a web server

esp32-firmware-update Update ESP32 firmware over WiFi from Github This includes a python script which generates the update json file based on the firm

Felix Biego 12 Dec 10, 2022
Tuya MCU SDK Arduino Library is developed based on the Tuya Wi-Fi general integration solution

Tuya MCU SDK Arduino Library is developed based on the Tuya Wi-Fi general integration solution. The device's MCU is connected to a Wi-Fi module through a serial port to implement a network connection. The development is based on general firmware, which supports the adaptative 9600 and115200 baud rate

Tuya 85 Dec 28, 2022
Single C file TLS 1.2/1.3 implementation, using tomcrypt as crypto library

TLSe Single C file TLS 1.3, 1.2, 1.1 and 1.0(without the weak ciphers) implementation, using libtomcrypt as crypto library. It also supports DTLS 1.2

Eduard Suica 481 Dec 31, 2022
C++11 implementation of Socket.IO client

By virtue of being written in C++, this client works in several different platforms. The examples folder contains an iPhone, QT and Console example chat client! It depends on websocket++ and is inspired by socket.io-clientpp.

Socket.IO 2k Jan 3, 2023
hessian2-codec it is a complete C++ implementation of hessian2 spec

hessian2-codec is a C++ library from Alibaba for hessian2 codec. It is a complete C++ implementation of hessian2 spec. Because it was originally intended to implement the Dubbo Filter of Envoy, it did not provide good support for serialization of user-defined types (there is only one way to implement user-defined types using ADL, but it is not very complete and does not support nested types well). At the moment it is simply deserializing content into some C++ intermediate types.

Alibaba 16 Nov 15, 2022
FreeModbus is a Modbus ASCII/RTU and Modbus TCP implementation for embedded systems

FreeModbus is a Modbus ASCII/RTU and Modbus TCP implementation for embedded systems. It provides an implementation of the Modbus Application Protocol

Mahmood Hosseini 22 Oct 11, 2022
Custom WebSocket implementation in C for educational and recreational purposes.

C WebSockets WARNING! The library is in an active development state and is not even alpha yet. Use it at your own risk. Nothing is documented, anythin

Tsoding 17 May 25, 2022
Backroll is a pure Rust implementation of GGPO rollback networking library.

backroll-rs Backroll is a pure Rust implementation of GGPO rollback networking library. Development Status This is still in an early beta stage. At ti

Hourai Teahouse 276 Jan 2, 2023
STARTTLS implementation for mail servers that don't have it.

smtpd-starttls-proxy - a STARTTLS implementation for mail servers ----------------------------------------------------------------- smtpd-starttls-p

Laurent Bercot 6 Dec 21, 2021
An Ace of Spades server implementation done in C

SpadesX What is SpadesX and why ? TL;DR Ace of Spades server written in C (Currently in full on development and thus early Alpha) Now if you would lik

null 38 Jan 5, 2023
An implementation of CBOR in C

CBOR This is a simple, small decoder for CBOR, the Concise Binary Object Representation. CBOR is defined by IETF RFC 8949, and Wikipedia has a good de

Kyunghwan Kwon 29 Dec 14, 2022
eBPF implementation that runs on top of Windows

eBPF for Windows eBPF is a well-known technology for providing programmability and agility, especially for extending an OS kernel, for use cases such

Microsoft 1.7k Jan 9, 2023