Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions arch/esp32/WireGuardESP32/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
Copyright (c) 2021 Kenta Ida (fuga@fugafuga.org)
Copyright (c) 2021 Daniel Hope (www.floorsense.nz)
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of "Floorsense Ltd", "Agile Workspace Ltd" nor the names of
its contributors may be used to endorse or promote products derived from this
software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Author: Daniel Hope <daniel.hope@smartalock.com>

12 changes: 12 additions & 0 deletions arch/esp32/WireGuardESP32/MESHCORETEL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# WireGuard ESP32 vendoring note

This directory is based on `ciniml/WireGuard-ESP32-Arduino` version 0.1.5 and
retains its BSD 3-Clause license.

MeshCoreTel carries two small local extensions used by the optional repeater
WireGuard target:

- an overload that accepts an IPv4 netmask and gateway, so the WireGuard
interface can own only the configured tunnel subnet while Wi-Fi remains the
default route;
- `peer_is_up()` status reporting with session/RX/TX ages for CLI diagnostics.
57 changes: 57 additions & 0 deletions arch/esp32/WireGuardESP32/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# WireGuard Implementation for ESP32 Arduino

This is an implementation of the [WireGuard&reg;](https://www.wireguard.com/) for ESP32 Arduino.

Almost all of this code is based on the [WireGuard Implementation for lwIP](https://github.com/smartalock/wireguard-lwip), but some potion of the code is adjusted to build with ESP32 Arduino.

## How to use

1. Include `WireGuard-ESP32.h` at the early part of the sketch.

```c++
#include <WireGuard-ESP32.h>
```

2. Define the instance of the `WireGuard` class at module level.

```c++
static WireGuard wg;
```

3. Connect to WiFi AP by using `WiFi` class.

```c++
WiFi.begin(ssid, password);
while( !WiFi.isConnected() ) {
delay(1000);
}
```

4. Sync the system time via NTP.

```c++
configTime(9 * 60 * 60, 0, "ntp.jst.mfeed.ad.jp", "ntp.nict.jp", "time.google.com");
```

5. Start the WireGuard interface.

```c++
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
10 changes: 10 additions & 0 deletions arch/esp32/WireGuardESP32/library.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
name=WireGuard-ESP32
version=0.1.5
author=Kenta Ida
maintainer=Kenta Ida <fuga@fugafuga.org>
sentence=WireGuard implementation for Arduino ESP32
paragraph=
category=Communication
url=https://github.com/ciniml/WireGuard-ESP32-Arduino
includes=WireGuard-ESP32.h
architectures=esp32,Inkplate
22 changes: 22 additions & 0 deletions arch/esp32/WireGuardESP32/src/WireGuard-ESP32.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
* WireGuard implementation for ESP32 Arduino by Kenta Ida (fuga@fugafuga.org)
* SPDX-License-Identifier: BSD-3-Clause
*/
#pragma once
#include <IPAddress.h>

class WireGuard
{
private:
bool _is_initialized = false;
public:
bool begin(const IPAddress& localIP, const char* privateKey, const char* remotePeerAddress, const char* remotePeerPublicKey, uint16_t remotePeerPort);
bool begin(const IPAddress& localIP, const IPAddress& subnet, const IPAddress& gateway,
const char* privateKey, const char* remotePeerAddress,
const char* remotePeerPublicKey, uint16_t remotePeerPort);
void end();
bool is_initialized() const { return this->_is_initialized; }
bool peer_is_up(uint32_t* session_age_ms = nullptr,
uint32_t* last_rx_age_ms = nullptr,
uint32_t* last_tx_age_ms = nullptr) const;
};
192 changes: 192 additions & 0 deletions arch/esp32/WireGuardESP32/src/WireGuard.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
/*
* WireGuard implementation for ESP32 Arduino by Kenta Ida (fuga@fugafuga.org)
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "WireGuard-ESP32.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"

#include "lwip/err.h"
#include "lwip/sys.h"
#include "lwip/ip.h"
#include "lwip/netdb.h"

#include "esp32-hal-log.h"

extern "C" {
#include "wireguardif.h"
#include "wireguard.h"
#include "wireguard-platform.h"
}

// Wireguard instance
static struct netif wg_netif_struct = {0};
static struct netif *wg_netif = NULL;
static struct netif *previous_default_netif = NULL;
static uint8_t wg_peer_index = WIREGUARDIF_INVALID_INDEX;

#define TAG "[WireGuard] "

bool WireGuard::begin(const IPAddress& localIP, const char* privateKey, const char* remotePeerAddress, const char* remotePeerPublicKey, uint16_t remotePeerPort) {
return begin(localIP, IPAddress(255, 255, 255, 255), IPAddress(0, 0, 0, 0),
privateKey, remotePeerAddress, remotePeerPublicKey, remotePeerPort);
}

bool WireGuard::begin(const IPAddress& localIP, const IPAddress& subnet, const IPAddress& gateway,
const char* privateKey, const char* remotePeerAddress,
const char* remotePeerPublicKey, uint16_t remotePeerPort) {
struct wireguardif_init_data wg;
struct wireguardif_peer peer;
ip_addr_t ipaddr = IPADDR4_INIT(static_cast<uint32_t>(localIP));
ip_addr_t netmask = IPADDR4_INIT(static_cast<uint32_t>(subnet));
ip_addr_t gateway_ip = IPADDR4_INIT(static_cast<uint32_t>(gateway));

assert(privateKey != NULL);
assert(remotePeerAddress != NULL);
assert(remotePeerPublicKey != NULL);
assert(remotePeerPort != 0);

// Setup the WireGuard device structure
wg.private_key = privateKey;
wg.listen_port = remotePeerPort;

wg.bind_netif = NULL;

// Initialise the first WireGuard peer structure
wireguardif_peer_init(&peer);
// If we know the endpoint's address can add here
bool success_get_endpoint_ip = false;
for(int retry = 0; retry < 5; retry++) {
ip_addr_t endpoint_ip = IPADDR4_INIT_BYTES(0, 0, 0, 0);
struct addrinfo *res = NULL;
struct addrinfo hint;
memset(&hint, 0, sizeof(hint));
memset(&endpoint_ip, 0, sizeof(endpoint_ip));
if( lwip_getaddrinfo(remotePeerAddress, NULL, &hint, &res) != 0 ) {
vTaskDelay(pdMS_TO_TICKS(2000));
continue;
}
success_get_endpoint_ip = true;
struct in_addr addr4 = ((struct sockaddr_in *) (res->ai_addr))->sin_addr;
inet_addr_to_ip4addr(ip_2_ip4(&endpoint_ip), &addr4);
lwip_freeaddrinfo(res);

peer.endpoint_ip = endpoint_ip;
log_i(TAG "%s is %3d.%3d.%3d.%3d"
, remotePeerAddress
, (endpoint_ip.u_addr.ip4.addr >> 0) & 0xff
, (endpoint_ip.u_addr.ip4.addr >> 8) & 0xff
, (endpoint_ip.u_addr.ip4.addr >> 16) & 0xff
, (endpoint_ip.u_addr.ip4.addr >> 24) & 0xff
);
break;
}
if( !success_get_endpoint_ip ) {
log_e(TAG "failed to get endpoint ip.");
return false;
}
// Register the new WireGuard network interface with lwIP
wg_netif = netif_add(&wg_netif_struct, ip_2_ip4(&ipaddr), ip_2_ip4(&netmask), ip_2_ip4(&gateway_ip), &wg, &wireguardif_init, &ip_input);
if( wg_netif == nullptr ) {
log_e(TAG "failed to initialize WG netif.");
return false;
}
// Mark the interface as administratively up, link up flag is set automatically when peer connects
netif_set_up(wg_netif);

peer.public_key = remotePeerPublicKey;
peer.preshared_key = NULL;
// Allow all IPs through tunnel
{
ip_addr_t allowed_ip = IPADDR4_INIT_BYTES(0, 0, 0, 0);
peer.allowed_ip = allowed_ip;
ip_addr_t allowed_mask = IPADDR4_INIT_BYTES(0, 0, 0, 0);
peer.allowed_mask = allowed_mask;
}

peer.endport_port = remotePeerPort;

// Initialize the platform
wireguard_platform_init();
// Register the new WireGuard peer with the netwok interface
wireguardif_add_peer(wg_netif, &peer, &wg_peer_index);
if ((wg_peer_index != WIREGUARDIF_INVALID_INDEX) && !ip_addr_isany(&peer.endpoint_ip)) {
// Start outbound connection to peer
log_i(TAG "connecting wireguard...");
wireguardif_connect(wg_netif, wg_peer_index);
// Save the current default interface for restoring when shutting down the WG interface.
previous_default_netif = netif_default;
// Set default interface to WG device.
netif_set_default(wg_netif);
}

this->_is_initialized = true;
return true;
}

void WireGuard::end() {
if( !this->_is_initialized ) return;

// Restore the default interface.
netif_set_default(previous_default_netif);
previous_default_netif = nullptr;
// Disconnect the WG interface.
wireguardif_disconnect(wg_netif, wg_peer_index);
// Remove peer from the WG interface
wireguardif_remove_peer(wg_netif, wg_peer_index);
wg_peer_index = WIREGUARDIF_INVALID_INDEX;
// Shutdown the wireguard interface.
wireguardif_shutdown(wg_netif);
// Remove the WG interface;
netif_remove(wg_netif);
wg_netif = nullptr;

this->_is_initialized = false;
}

bool WireGuard::peer_is_up(uint32_t* session_age_ms,
uint32_t* last_rx_age_ms,
uint32_t* last_tx_age_ms) const {
const uint32_t none = 0xFFFFFFFFUL;
if (session_age_ms) *session_age_ms = none;
if (last_rx_age_ms) *last_rx_age_ms = none;
if (last_tx_age_ms) *last_tx_age_ms = none;

if (!this->_is_initialized || wg_netif == nullptr ||
wg_peer_index == WIREGUARDIF_INVALID_INDEX ||
wg_netif->state == nullptr) {
return false;
}

if (wireguardif_peer_is_up(wg_netif, wg_peer_index, nullptr, nullptr) != ERR_OK) {
return false;
}

struct wireguard_device* device =
static_cast<struct wireguard_device*>(wg_netif->state);
if (wg_peer_index >= WIREGUARD_MAX_PEERS) return false;

struct wireguard_peer* peer = &device->peers[wg_peer_index];
const struct wireguard_keypair* keypair = nullptr;
if (peer->curr_keypair.valid) {
keypair = &peer->curr_keypair;
} else if (peer->prev_keypair.valid) {
keypair = &peer->prev_keypair;
}
if (keypair == nullptr) return false;

const uint32_t now = wireguard_sys_now();
if (session_age_ms && keypair->keypair_millis != 0) {
*session_age_ms = now - keypair->keypair_millis;
}
if (last_rx_age_ms && peer->last_rx != 0) {
*last_rx_age_ms = now - peer->last_rx;
}
if (last_tx_age_ms && peer->last_tx != 0) {
*last_tx_age_ms = now - peer->last_tx;
}
return true;
}
23 changes: 23 additions & 0 deletions arch/esp32/WireGuardESP32/src/crypto.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#include "crypto.h"

#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>

void crypto_zero(void *dest, size_t len) {
volatile uint8_t *p = (uint8_t *)dest;
while (len--) {
*p++ = 0;
}
}

bool crypto_equal(const void *a, const void *b, size_t size) {
uint8_t neq = 0;
while (size > 0) {
neq |= *(uint8_t *)a ^ *(uint8_t *)b;
a += 1;
b += 1;
size -= 1;
}
return (neq) ? false : true;
}
Loading