Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement WireGuard VPN #585

Merged
merged 3 commits into from
Dec 1, 2023
Merged
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
2 changes: 1 addition & 1 deletion data/en.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"en":{"language":"English","home":{"title":"Main Menu","btn":"Main Menu","nav":"Home"},"save":"Save Settings","user":"Username","pass":"Password","hasp":{"title":"HASP Design","btn":"HASP Design","theme":"UI Theme","color1":"Primary color","color2":"Secondary color","pages":"Start Layout","font":"Default Font","startpage":"Startup Page","startdim":"Startup Dim"},"screenshot":{"title":"Screenshot","btn":"Screenshot","nav":"Screenshot","prev":"Prev Page","next":"Next Page","refresh":"Refresh"},"info":{"title":"Information","btn":"Information","nav":"Information"},"config":{"title":"Configuration","btn":"Configuration","nav":"Settings"},"ota":{"title":"Firmware Update","btn":"Firmware Update","nav":"Firmware","submit":"Update Firmware","file":"Firmware File","url":"Firmware URL","redirect":"Follow Redirects","never":"Never","strict":"Strict","always":"Always"},"editor":{"title":"File Editor","btn":"File Editor","nav":"File Editor"},"reset":{"title":"Factory Reset","btn":"Factory Reset","warning":"Warning","message":"This process will reset all settings to the default values. The internal flash will be erased and the device is restarted. You may need to connect to the WiFi AP displayed on the panel to reconfigure the device before accessing it again.","fileloss":"ALL FILES WILL BE LOST!"},"reboot":{"title":"Rebooting...","btn":"Restart","nav":"Reboot","message":"The device is rebooting."},"about":{"credits":"Based on the previous work of the following open source developers:","copyright":"Copyright ","rights":"All rights reserved.","clause1":"Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:","clause2":"The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.","clause3":"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.","mit":"MIT License","bsd":"BSD License","freebsd":"FreeBSD License","apache2":"Apache2 License"},"wifi":{"title":"Wifi Settings","btn":"Wifi Settings","ssid":"SSID"},"mqtt":{"title":"MQTT Settings","btn":"MQTT Settings","name":"Hostname","group":"Groupname","host":"Broker","port":"Port","node_t":"Node Topic","group_t":"Group Topic","broadcast_t":"Broadcast Topic","hass_t":"HA LWT Topic"},"http":{"title":"HTTP Settings","btn":"HTTP Settings"},"ftp":{"title":"FTP Settings","btn":"FTP Settings","port":"FTP Port","pasv":"Passive Port"},"gui":{"title":"Display Settings","btn":"Display Settings","antiburn":"Antiburn","calibrate":"Calibrate"},"gpio":"GPIO Settings","debug":{"title":"Debug Settings","btn":"Debug Settings","baud":"Baudrate","tele":"Tele Period","ansi":"Use ANSI codes","host":"Syslog Server","port":"Syslog Port","ietf":"IETF (RFC 5424)","bsd":"BSD (RFC 3164)","log":"Facility"},"time":{"title":"Time Settings","btn":"Time Settings","region":"Region","zone":"Timezone","tz":"Timezone","ntp":"NTP Servers"},"region":{"etc":"Etcetera ","continents":"Continents ","af":"Africa ","as":"Asia ","au":"Australia ","aq":"Antarctica ","eu":"Europe ","na":"North America ","sa":"South America ","islands":"Islands ","at":"Atlantic Ocean ","in":"Indian Ocean ","pa":"Pacific Ocean "}}}
{"en":{"language":"English","home":{"title":"Main Menu","btn":"Main Menu","nav":"Home"},"save":"Save Settings","user":"Username","pass":"Password","hasp":{"title":"HASP Design","btn":"HASP Design","theme":"UI Theme","color1":"Primary color","color2":"Secondary color","pages":"Start Layout","font":"Default Font","startpage":"Startup Page","startdim":"Startup Dim"},"screenshot":{"title":"Screenshot","btn":"Screenshot","nav":"Screenshot","prev":"Prev Page","next":"Next Page","refresh":"Refresh"},"info":{"title":"Information","btn":"Information","nav":"Information"},"config":{"title":"Configuration","btn":"Configuration","nav":"Settings"},"ota":{"title":"Firmware Update","btn":"Firmware Update","nav":"Firmware","submit":"Update Firmware","file":"Firmware File","url":"Firmware URL","redirect":"Follow Redirects","never":"Never","strict":"Strict","always":"Always"},"editor":{"title":"File Editor","btn":"File Editor","nav":"File Editor"},"reset":{"title":"Factory Reset","btn":"Factory Reset","warning":"Warning","message":"This process will reset all settings to the default values. The internal flash will be erased and the device is restarted. You may need to connect to the WiFi AP displayed on the panel to reconfigure the device before accessing it again.","fileloss":"ALL FILES WILL BE LOST!"},"reboot":{"title":"Rebooting...","btn":"Restart","nav":"Reboot","message":"The device is rebooting."},"about":{"credits":"Based on the previous work of the following open source developers:","copyright":"Copyright ","rights":"All rights reserved.","clause1":"Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:","clause2":"The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.","clause3":"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.","mit":"MIT License","bsd":"BSD License","freebsd":"FreeBSD License","apache2":"Apache2 License"},"wifi":{"title":"Wifi Settings","btn":"Wifi Settings","ssid":"SSID"},"wg":{"title":"WireGuard Settings","btn":"WireGuard Settings","vpnip":"VPN IP","privkey":"Private Key","host":"Remote IP","port":"Remote Port","pubkey":"Remote Public Key"},"mqtt":{"title":"MQTT Settings","btn":"MQTT Settings","name":"Hostname","group":"Groupname","host":"Broker","port":"Port","node_t":"Node Topic","group_t":"Group Topic","broadcast_t":"Broadcast Topic","hass_t":"HA LWT Topic"},"http":{"title":"HTTP Settings","btn":"HTTP Settings"},"ftp":{"title":"FTP Settings","btn":"FTP Settings","port":"FTP Port","pasv":"Passive Port"},"gui":{"title":"Display Settings","btn":"Display Settings","antiburn":"Antiburn","calibrate":"Calibrate"},"gpio":"GPIO Settings","debug":{"title":"Debug Settings","btn":"Debug Settings","baud":"Baudrate","tele":"Tele Period","ansi":"Use ANSI codes","host":"Syslog Server","port":"Syslog Port","ietf":"IETF (RFC 5424)","bsd":"BSD (RFC 3164)","log":"Facility"},"time":{"title":"Time Settings","btn":"Time Settings","region":"Region","zone":"Timezone","tz":"Timezone","ntp":"NTP Servers"},"region":{"etc":"Etcetera ","continents":"Continents ","af":"Africa ","as":"Asia ","au":"Australia ","aq":"Antarctica ","eu":"Europe ","na":"North America ","sa":"South America ","islands":"Islands ","at":"Atlantic Ocean ","in":"Indian Ocean ","pa":"Pacific Ocean "}}}
2 changes: 1 addition & 1 deletion data/main.js

Large diffs are not rendered by default.

8 changes: 8 additions & 0 deletions include/hasp_conf.h
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@
#define HASP_USE_MQTT (HASP_HAS_NETWORK)
#endif

#ifndef HASP_USE_WIREGUARD
#define HASP_USE_WIREGUARD (HASP_HAS_NETWORK)
#endif

#ifndef HASP_USE_BROADCAST
#define HASP_USE_BROADCAST 1
#endif
Expand Down Expand Up @@ -232,6 +236,10 @@ static WiFiSpiClass WiFi;
#endif
#endif // HASP_USE_WIFI

#if HASP_USE_WIREGUARD > 0
#include "sys/net/hasp_wireguard.h"
#endif

#if HASP_USE_ETHERNET > 0
#if defined(ARDUINO_ARCH_ESP32)
#include "sys/net/hasp_ethernet_esp32.h"
Expand Down
1 change: 1 addition & 0 deletions lib/WireGuard-ESP32/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
build.sh
28 changes: 28 additions & 0 deletions lib/WireGuard-ESP32/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
Copyright (c) 2021 Kenta Ida ([email protected])
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 <[email protected]>

57 changes: 57 additions & 0 deletions lib/WireGuard-ESP32/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 lib/WireGuard-ESP32/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 <[email protected]>
sentence=WireGuard implementation for Arduino ESP32
paragraph=
category=Communication
url=https://github.com/ciniml/WireGuard-ESP32-Arduino
includes=WireGuard-ESP32.h
architectures=esp32,Inkplate
17 changes: 17 additions & 0 deletions lib/WireGuard-ESP32/src/WireGuard-ESP32.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
* WireGuard implementation for ESP32 Arduino by Kenta Ida ([email protected])
* 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 IPAddress& Subnet, const IPAddress& Gateway, const char* privateKey, const char* remotePeerAddress, const char* remotePeerPublicKey, uint16_t remotePeerPort);
bool begin(const IPAddress& localIP, const char* privateKey, const char* remotePeerAddress, const char* remotePeerPublicKey, uint16_t remotePeerPort);
void end();
bool is_initialized() const { return this->_is_initialized; }
};
147 changes: 147 additions & 0 deletions lib/WireGuard-ESP32/src/WireGuard.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
/*
* WireGuard implementation for ESP32 Arduino by Kenta Ida ([email protected])
* 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-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 wireguard_peer_index = WIREGUARDIF_INVALID_INDEX;

#define TAG "[WireGuard] "

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 = 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), &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, &wireguard_peer_index);
if ((wireguard_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, wireguard_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;
}

bool WireGuard::begin(const IPAddress& localIP, const char* privateKey, const char* remotePeerAddress, const char* remotePeerPublicKey, uint16_t remotePeerPort) {
// Maintain compatiblity with old begin
auto subnet = IPAddress(255,255,255,255);
auto gateway = IPAddress(0,0,0,0);
return WireGuard::begin(localIP, subnet, gateway, privateKey, remotePeerAddress, remotePeerPublicKey, remotePeerPort);
}

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, wireguard_peer_index);
// Remove peer from the WG interface
wireguardif_remove_peer(wg_netif, wireguard_peer_index);
wireguard_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;
}
23 changes: 23 additions & 0 deletions lib/WireGuard-ESP32/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