From 45dd1ed4382aa4a7cbc72b6dabb3cad958943a1b Mon Sep 17 00:00:00 2001 From: Jaroslav Kysela Date: Wed, 29 Nov 2023 20:41:28 +0100 Subject: [PATCH 1/3] Add wireguard library from https://github.com/ciniml/WireGuard-ESP32-Arduino --- lib/WireGuard-ESP32/.gitignore | 1 + lib/WireGuard-ESP32/LICENSE | 28 + lib/WireGuard-ESP32/README.md | 57 + lib/WireGuard-ESP32/library.properties | 10 + lib/WireGuard-ESP32/src/WireGuard-ESP32.h | 17 + lib/WireGuard-ESP32/src/WireGuard.cpp | 147 +++ lib/WireGuard-ESP32/src/crypto.c | 23 + lib/WireGuard-ESP32/src/crypto.h | 102 ++ lib/WireGuard-ESP32/src/crypto/refc/blake2s.c | 156 +++ lib/WireGuard-ESP32/src/crypto/refc/blake2s.h | 39 + .../src/crypto/refc/chacha20.c | 202 +++ .../src/crypto/refc/chacha20.h | 53 + .../src/crypto/refc/chacha20poly1305.c | 193 +++ .../src/crypto/refc/chacha20poly1305.h | 50 + .../src/crypto/refc/poly1305-donna-32.h | 220 ++++ .../src/crypto/refc/poly1305-donna.c | 41 + .../src/crypto/refc/poly1305-donna.h | 16 + .../src/crypto/refc/x25519-license.txt | 21 + lib/WireGuard-ESP32/src/crypto/refc/x25519.c | 448 +++++++ lib/WireGuard-ESP32/src/crypto/refc/x25519.h | 129 ++ lib/WireGuard-ESP32/src/wireguard-platform.c | 68 + lib/WireGuard-ESP32/src/wireguard-platform.h | 71 ++ lib/WireGuard-ESP32/src/wireguard.c | 1129 +++++++++++++++++ lib/WireGuard-ESP32/src/wireguard.h | 287 +++++ lib/WireGuard-ESP32/src/wireguardif.c | 1028 +++++++++++++++ lib/WireGuard-ESP32/src/wireguardif.h | 137 ++ 26 files changed, 4673 insertions(+) create mode 100644 lib/WireGuard-ESP32/.gitignore create mode 100644 lib/WireGuard-ESP32/LICENSE create mode 100644 lib/WireGuard-ESP32/README.md create mode 100644 lib/WireGuard-ESP32/library.properties create mode 100644 lib/WireGuard-ESP32/src/WireGuard-ESP32.h create mode 100644 lib/WireGuard-ESP32/src/WireGuard.cpp create mode 100644 lib/WireGuard-ESP32/src/crypto.c create mode 100644 lib/WireGuard-ESP32/src/crypto.h create mode 100644 lib/WireGuard-ESP32/src/crypto/refc/blake2s.c create mode 100644 lib/WireGuard-ESP32/src/crypto/refc/blake2s.h create mode 100644 lib/WireGuard-ESP32/src/crypto/refc/chacha20.c create mode 100644 lib/WireGuard-ESP32/src/crypto/refc/chacha20.h create mode 100644 lib/WireGuard-ESP32/src/crypto/refc/chacha20poly1305.c create mode 100644 lib/WireGuard-ESP32/src/crypto/refc/chacha20poly1305.h create mode 100644 lib/WireGuard-ESP32/src/crypto/refc/poly1305-donna-32.h create mode 100644 lib/WireGuard-ESP32/src/crypto/refc/poly1305-donna.c create mode 100644 lib/WireGuard-ESP32/src/crypto/refc/poly1305-donna.h create mode 100644 lib/WireGuard-ESP32/src/crypto/refc/x25519-license.txt create mode 100644 lib/WireGuard-ESP32/src/crypto/refc/x25519.c create mode 100644 lib/WireGuard-ESP32/src/crypto/refc/x25519.h create mode 100644 lib/WireGuard-ESP32/src/wireguard-platform.c create mode 100644 lib/WireGuard-ESP32/src/wireguard-platform.h create mode 100644 lib/WireGuard-ESP32/src/wireguard.c create mode 100644 lib/WireGuard-ESP32/src/wireguard.h create mode 100644 lib/WireGuard-ESP32/src/wireguardif.c create mode 100644 lib/WireGuard-ESP32/src/wireguardif.h diff --git a/lib/WireGuard-ESP32/.gitignore b/lib/WireGuard-ESP32/.gitignore new file mode 100644 index 000000000..c07a74de4 --- /dev/null +++ b/lib/WireGuard-ESP32/.gitignore @@ -0,0 +1 @@ +build.sh \ No newline at end of file diff --git a/lib/WireGuard-ESP32/LICENSE b/lib/WireGuard-ESP32/LICENSE new file mode 100644 index 000000000..3856ceb1a --- /dev/null +++ b/lib/WireGuard-ESP32/LICENSE @@ -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 + diff --git a/lib/WireGuard-ESP32/README.md b/lib/WireGuard-ESP32/README.md new file mode 100644 index 000000000..25424faab --- /dev/null +++ b/lib/WireGuard-ESP32/README.md @@ -0,0 +1,57 @@ +# WireGuard Implementation for ESP32 Arduino + +This is an implementation of the [WireGuard®](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 +``` + +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 diff --git a/lib/WireGuard-ESP32/library.properties b/lib/WireGuard-ESP32/library.properties new file mode 100644 index 000000000..d51576d68 --- /dev/null +++ b/lib/WireGuard-ESP32/library.properties @@ -0,0 +1,10 @@ +name=WireGuard-ESP32 +version=0.1.5 +author=Kenta Ida +maintainer=Kenta Ida +sentence=WireGuard implementation for Arduino ESP32 +paragraph= +category=Communication +url=https://github.com/ciniml/WireGuard-ESP32-Arduino +includes=WireGuard-ESP32.h +architectures=esp32,Inkplate diff --git a/lib/WireGuard-ESP32/src/WireGuard-ESP32.h b/lib/WireGuard-ESP32/src/WireGuard-ESP32.h new file mode 100644 index 000000000..b30c884ab --- /dev/null +++ b/lib/WireGuard-ESP32/src/WireGuard-ESP32.h @@ -0,0 +1,17 @@ +/* + * WireGuard implementation for ESP32 Arduino by Kenta Ida (fuga@fugafuga.org) + * SPDX-License-Identifier: BSD-3-Clause + */ +#pragma once +#include + +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; } +}; diff --git a/lib/WireGuard-ESP32/src/WireGuard.cpp b/lib/WireGuard-ESP32/src/WireGuard.cpp new file mode 100644 index 000000000..ce69650e9 --- /dev/null +++ b/lib/WireGuard-ESP32/src/WireGuard.cpp @@ -0,0 +1,147 @@ +/* + * 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-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(localIP)); + ip_addr_t netmask = IPADDR4_INIT(static_cast(Subnet)); + ip_addr_t gateway = IPADDR4_INIT(static_cast(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; +} \ No newline at end of file diff --git a/lib/WireGuard-ESP32/src/crypto.c b/lib/WireGuard-ESP32/src/crypto.c new file mode 100644 index 000000000..3597b86b0 --- /dev/null +++ b/lib/WireGuard-ESP32/src/crypto.c @@ -0,0 +1,23 @@ +#include "crypto.h" + +#include +#include +#include + +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; +} diff --git a/lib/WireGuard-ESP32/src/crypto.h b/lib/WireGuard-ESP32/src/crypto.h new file mode 100644 index 000000000..c5d640d58 --- /dev/null +++ b/lib/WireGuard-ESP32/src/crypto.h @@ -0,0 +1,102 @@ +#ifndef _CRYPTO_H_ +#define _CRYPTO_H_ + +#include +#include +#include + +// BLAKE2S IMPLEMENTATION +#include "crypto/refc/blake2s.h" +#define wireguard_blake2s_ctx blake2s_ctx +#define wireguard_blake2s_init(ctx,outlen,key,keylen) blake2s_init(ctx,outlen,key,keylen) +#define wireguard_blake2s_update(ctx,in,inlen) blake2s_update(ctx,in,inlen) +#define wireguard_blake2s_final(ctx,out) blake2s_final(ctx,out) +#define wireguard_blake2s(out,outlen,key,keylen,in,inlen) blake2s(out,outlen,key,keylen,in,inlen) + +// X25519 IMPLEMENTATION +#include "crypto/refc/x25519.h" +#define wireguard_x25519(a,b,c) x25519(a,b,c,1) + +// CHACHA20POLY1305 IMPLEMENTATION +#include "crypto/refc/chacha20poly1305.h" +#define wireguard_aead_encrypt(dst,src,srclen,ad,adlen,nonce,key) chacha20poly1305_encrypt(dst,src,srclen,ad,adlen,nonce,key) +#define wireguard_aead_decrypt(dst,src,srclen,ad,adlen,nonce,key) chacha20poly1305_decrypt(dst,src,srclen,ad,adlen,nonce,key) +#define wireguard_xaead_encrypt(dst,src,srclen,ad,adlen,nonce,key) xchacha20poly1305_encrypt(dst,src,srclen,ad,adlen,nonce,key) +#define wireguard_xaead_decrypt(dst,src,srclen,ad,adlen,nonce,key) xchacha20poly1305_decrypt(dst,src,srclen,ad,adlen,nonce,key) + + +// Endian / unaligned helper macros +#define U8C(v) (v##U) +#define U32C(v) (v##U) + +#define U8V(v) ((uint8_t)(v) & U8C(0xFF)) +#define U32V(v) ((uint32_t)(v) & U32C(0xFFFFFFFF)) + +#define U8TO32_LITTLE(p) \ + (((uint32_t)((p)[0]) ) | \ + ((uint32_t)((p)[1]) << 8) | \ + ((uint32_t)((p)[2]) << 16) | \ + ((uint32_t)((p)[3]) << 24)) + +#define U8TO64_LITTLE(p) \ + (((uint64_t)((p)[0]) ) | \ + ((uint64_t)((p)[1]) << 8) | \ + ((uint64_t)((p)[2]) << 16) | \ + ((uint64_t)((p)[3]) << 24) | \ + ((uint64_t)((p)[4]) << 32) | \ + ((uint64_t)((p)[5]) << 40) | \ + ((uint64_t)((p)[6]) << 48) | \ + ((uint64_t)((p)[7]) << 56)) + +#define U16TO8_BIG(p, v) \ + do { \ + (p)[1] = U8V((v) ); \ + (p)[0] = U8V((v) >> 8); \ + } while (0) + +#define U32TO8_LITTLE(p, v) \ + do { \ + (p)[0] = U8V((v) ); \ + (p)[1] = U8V((v) >> 8); \ + (p)[2] = U8V((v) >> 16); \ + (p)[3] = U8V((v) >> 24); \ + } while (0) + +#define U32TO8_BIG(p, v) \ + do { \ + (p)[3] = U8V((v) ); \ + (p)[2] = U8V((v) >> 8); \ + (p)[1] = U8V((v) >> 16); \ + (p)[0] = U8V((v) >> 24); \ + } while (0) + +#define U64TO8_LITTLE(p, v) \ + do { \ + (p)[0] = U8V((v) ); \ + (p)[1] = U8V((v) >> 8); \ + (p)[2] = U8V((v) >> 16); \ + (p)[3] = U8V((v) >> 24); \ + (p)[4] = U8V((v) >> 32); \ + (p)[5] = U8V((v) >> 40); \ + (p)[6] = U8V((v) >> 48); \ + (p)[7] = U8V((v) >> 56); \ +} while (0) + +#define U64TO8_BIG(p, v) \ + do { \ + (p)[7] = U8V((v) ); \ + (p)[6] = U8V((v) >> 8); \ + (p)[5] = U8V((v) >> 16); \ + (p)[4] = U8V((v) >> 24); \ + (p)[3] = U8V((v) >> 32); \ + (p)[2] = U8V((v) >> 40); \ + (p)[1] = U8V((v) >> 48); \ + (p)[0] = U8V((v) >> 56); \ +} while (0) + + +void crypto_zero(void *dest, size_t len); +bool crypto_equal(const void *a, const void *b, size_t size); + +#endif /* _CRYPTO_H_ */ + diff --git a/lib/WireGuard-ESP32/src/crypto/refc/blake2s.c b/lib/WireGuard-ESP32/src/crypto/refc/blake2s.c new file mode 100644 index 000000000..ae5e14ca5 --- /dev/null +++ b/lib/WireGuard-ESP32/src/crypto/refc/blake2s.c @@ -0,0 +1,156 @@ +// Taken from RFC7693 - https://tools.ietf.org/html/rfc7693 + +#include "blake2s.h" +#include "../../crypto.h" + +// Cyclic right rotation. + +#ifndef ROTR32 +#define ROTR32(x, y) (((x) >> (y)) ^ ((x) << (32 - (y)))) +#endif + +// Mixing function G. +#define B2S_G(a, b, c, d, x, y) { \ + v[a] = v[a] + v[b] + x; \ + v[d] = ROTR32(v[d] ^ v[a], 16); \ + v[c] = v[c] + v[d]; \ + v[b] = ROTR32(v[b] ^ v[c], 12); \ + v[a] = v[a] + v[b] + y; \ + v[d] = ROTR32(v[d] ^ v[a], 8); \ + v[c] = v[c] + v[d]; \ + v[b] = ROTR32(v[b] ^ v[c], 7); } + +// Initialization Vector. +static const uint32_t blake2s_iv[8] = +{ + 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, + 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19 +}; + +// Compression function. "last" flag indicates last block. +static void blake2s_compress(blake2s_ctx *ctx, int last) +{ + const uint8_t sigma[10][16] = { + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, + { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, + { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, + { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, + { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, + { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, + { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, + { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, + { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, + { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 } + }; + int i; + uint32_t v[16], m[16]; + + for (i = 0; i < 8; i++) { // init work variables + v[i] = ctx->h[i]; + v[i + 8] = blake2s_iv[i]; + } + + v[12] ^= ctx->t[0]; // low 32 bits of offset + v[13] ^= ctx->t[1]; // high 32 bits + if (last) // last block flag set ? + v[14] = ~v[14]; + for (i = 0; i < 16; i++) // get little-endian words + m[i] = U8TO32_LITTLE(&ctx->b[4 * i]); + + for (i = 0; i < 10; i++) { // ten rounds + B2S_G( 0, 4, 8, 12, m[sigma[i][ 0]], m[sigma[i][ 1]]); + B2S_G( 1, 5, 9, 13, m[sigma[i][ 2]], m[sigma[i][ 3]]); + B2S_G( 2, 6, 10, 14, m[sigma[i][ 4]], m[sigma[i][ 5]]); + B2S_G( 3, 7, 11, 15, m[sigma[i][ 6]], m[sigma[i][ 7]]); + B2S_G( 0, 5, 10, 15, m[sigma[i][ 8]], m[sigma[i][ 9]]); + B2S_G( 1, 6, 11, 12, m[sigma[i][10]], m[sigma[i][11]]); + B2S_G( 2, 7, 8, 13, m[sigma[i][12]], m[sigma[i][13]]); + B2S_G( 3, 4, 9, 14, m[sigma[i][14]], m[sigma[i][15]]); + } + + for( i = 0; i < 8; ++i ) + ctx->h[i] ^= v[i] ^ v[i + 8]; +} + +// Initialize the hashing context "ctx" with optional key "key". +// 1 <= outlen <= 32 gives the digest size in bytes. +// Secret key (also <= 32 bytes) is optional (keylen = 0). +int blake2s_init(blake2s_ctx *ctx, size_t outlen, + const void *key, size_t keylen) // (keylen=0: no key) +{ + size_t i; + + if (outlen == 0 || outlen > 32 || keylen > 32) + return -1; // illegal parameters + + for (i = 0; i < 8; i++) // state, "param block" + ctx->h[i] = blake2s_iv[i]; + ctx->h[0] ^= 0x01010000 ^ (keylen << 8) ^ outlen; + + ctx->t[0] = 0; // input count low word + ctx->t[1] = 0; // input count high word + ctx->c = 0; // pointer within buffer + ctx->outlen = outlen; + + for (i = keylen; i < 64; i++) // zero input block + ctx->b[i] = 0; + if (keylen > 0) { + blake2s_update(ctx, key, keylen); + ctx->c = 64; // at the end + } + + return 0; +} + +// Add "inlen" bytes from "in" into the hash. +void blake2s_update(blake2s_ctx *ctx, + const void *in, size_t inlen) // data bytes +{ + size_t i; + + for (i = 0; i < inlen; i++) { + if (ctx->c == 64) { // buffer full ? + ctx->t[0] += ctx->c; // add counters + if (ctx->t[0] < ctx->c) // carry overflow ? + ctx->t[1]++; // high word + blake2s_compress(ctx, 0); // compress (not last) + ctx->c = 0; // counter to zero + } + ctx->b[ctx->c++] = ((const uint8_t *) in)[i]; + } +} + +// Generate the message digest (size given in init). +// Result placed in "out". +void blake2s_final(blake2s_ctx *ctx, void *out) +{ + size_t i; + + ctx->t[0] += ctx->c; // mark last block offset + if (ctx->t[0] < ctx->c) // carry overflow + ctx->t[1]++; // high word + + while (ctx->c < 64) // fill up with zeros + ctx->b[ctx->c++] = 0; + blake2s_compress(ctx, 1); // final block flag = 1 + + // little endian convert and store + for (i = 0; i < ctx->outlen; i++) { + ((uint8_t *) out)[i] = + (ctx->h[i >> 2] >> (8 * (i & 3))) & 0xFF; + } +} + +// Convenience function for all-in-one computation. +int blake2s(void *out, size_t outlen, + const void *key, size_t keylen, + const void *in, size_t inlen) +{ + blake2s_ctx ctx; + if (blake2s_init(&ctx, outlen, key, keylen)) + return -1; + blake2s_update(&ctx, in, inlen); + blake2s_final(&ctx, out); + + return 0; +} diff --git a/lib/WireGuard-ESP32/src/crypto/refc/blake2s.h b/lib/WireGuard-ESP32/src/crypto/refc/blake2s.h new file mode 100644 index 000000000..4b056467a --- /dev/null +++ b/lib/WireGuard-ESP32/src/crypto/refc/blake2s.h @@ -0,0 +1,39 @@ +// Taken from RFC7693 - https://tools.ietf.org/html/rfc7693 +// BLAKE2s Hashing Context and API Prototypes +#ifndef _BLAKE2S_H +#define _BLAKE2S_H + +#define BLAKE2S_BLOCK_SIZE 64 + +#include +#include + +// state context +typedef struct { + uint8_t b[64]; // input buffer + uint32_t h[8]; // chained state + uint32_t t[2]; // total number of bytes + size_t c; // pointer for b[] + size_t outlen; // digest size +} blake2s_ctx; + +// Initialize the hashing context "ctx" with optional key "key". +// 1 <= outlen <= 32 gives the digest size in bytes. +// Secret key (also <= 32 bytes) is optional (keylen = 0). +int blake2s_init(blake2s_ctx *ctx, size_t outlen, + const void *key, size_t keylen); // secret key + +// Add "inlen" bytes from "in" into the hash. +void blake2s_update(blake2s_ctx *ctx, // context + const void *in, size_t inlen); // data to be hashed + +// Generate the message digest (size given in init). +// Result placed in "out". +void blake2s_final(blake2s_ctx *ctx, void *out); + +// All-in-one convenience function. +int blake2s(void *out, size_t outlen, // return buffer for digest + const void *key, size_t keylen, // optional secret key + const void *in, size_t inlen); // data to be hashed + +#endif diff --git a/lib/WireGuard-ESP32/src/crypto/refc/chacha20.c b/lib/WireGuard-ESP32/src/crypto/refc/chacha20.c new file mode 100644 index 000000000..52c4dd6ee --- /dev/null +++ b/lib/WireGuard-ESP32/src/crypto/refc/chacha20.c @@ -0,0 +1,202 @@ +/* + * 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. 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 + */ + +// RFC7539 implementation of ChaCha20 with modified nonce size for WireGuard +// https://tools.ietf.org/html/rfc7539 +// Adapted from https://cr.yp.to/streamciphers/timings/estreambench/submissions/salsa20/chacha8/ref/chacha.c by D. J. Bernstein (Public Domain) +// HChaCha20 is described here: https://tools.ietf.org/id/draft-arciszewski-xchacha-02.html + +#include "chacha20.h" + +#include +#include +#include "../../crypto.h" + +// 2.3. The ChaCha20 Block Function +// The first four words (0-3) are constants: 0x61707865, 0x3320646e, 0x79622d32, 0x6b206574 +static const uint32_t CHACHA20_CONSTANT_1 = 0x61707865; +static const uint32_t CHACHA20_CONSTANT_2 = 0x3320646e; +static const uint32_t CHACHA20_CONSTANT_3 = 0x79622d32; +static const uint32_t CHACHA20_CONSTANT_4 = 0x6b206574; + +#define ROTL32(v, n) (U32V((v) << (n)) | ((v) >> (32 - (n)))) + +#define PLUS(v,w) (U32V((v) + (w))) +#define PLUSONE(v) (PLUS((v),1)) + +// 2.1. The ChaCha Quarter Round +// 1. a += b; d ^= a; d <<<= 16; +// 2. c += d; b ^= c; b <<<= 12; +// 3. a += b; d ^= a; d <<<= 8; +// 4. c += d; b ^= c; b <<<= 7; + +#define QUARTERROUND(a, b, c, d) \ + a += b; d ^= a; d = ROTL32(d, 16); \ + c += d; b ^= c; b = ROTL32(b, 12); \ + a += b; d ^= a; d = ROTL32(d, 8); \ + c += d; b ^= c; b = ROTL32(b, 7) + +static inline void INNER_BLOCK(uint32_t *block) { + QUARTERROUND(block[0], block[4], block[ 8], block[12]); // column 0 + QUARTERROUND(block[1], block[5], block[ 9], block[13]); // column 1 + QUARTERROUND(block[2], block[6], block[10], block[14]); // column 2 + QUARTERROUND(block[3], block[7], block[11], block[15]); // column 3 + QUARTERROUND(block[0], block[5], block[10], block[15]); // diagonal 1 + QUARTERROUND(block[1], block[6], block[11], block[12]); // diagonal 2 + QUARTERROUND(block[2], block[7], block[ 8], block[13]); // diagonal 3 + QUARTERROUND(block[3], block[4], block[ 9], block[14]); // diagonal 4 +} + +#define TWENTY_ROUNDS(x) ( \ + INNER_BLOCK(x), \ + INNER_BLOCK(x), \ + INNER_BLOCK(x), \ + INNER_BLOCK(x), \ + INNER_BLOCK(x), \ + INNER_BLOCK(x), \ + INNER_BLOCK(x), \ + INNER_BLOCK(x), \ + INNER_BLOCK(x), \ + INNER_BLOCK(x) \ +) + +// 2.3. The ChaCha20 Block Function +// chacha20_block(key, counter, nonce): +// state = constants | key | counter | nonce +// working_state = state +// for i=1 upto 10 +// inner_block(working_state) +// end +// state += working_state +// return serialize(state) +// end +static void chacha20_block(struct chacha20_ctx *ctx, uint8_t *stream) { + uint32_t working_state[16]; + int i; + + for (i = 0; i < 16; ++i) { + working_state[i] = ctx->state[i]; + } + + TWENTY_ROUNDS(working_state); + + for (i = 0; i < 16; ++i) { + U32TO8_LITTLE(stream + (4 * i), PLUS(working_state[i], ctx->state[i])); + } +} + +void chacha20(struct chacha20_ctx *ctx, uint8_t *out, const uint8_t *in, uint32_t len) { + uint8_t output[CHACHA20_BLOCK_SIZE]; + int i; + + if (len) { + for (;;) { + chacha20_block(ctx, output); + // Word 12 is a block counter + ctx->state[12] = PLUSONE(ctx->state[12]); + if (len <= 64) { + for (i = 0;i < len;++i) { + out[i] = in[i] ^ output[i]; + } + return; + } + for (i = 0;i < 64;++i) { + out[i] = in[i] ^ output[i]; + } + len -= 64; + out += 64; + in += 64; + } + } +} + + +// 2.3. The ChaCha20 Block Function +// The first four words (0-3) are constants: 0x61707865, 0x3320646e, 0x79622d32, 0x6b206574 +// The next eight words (4-11) are taken from the 256-bit key by reading the bytes in little-endian order, in 4-byte chunks. +// Word 12 is a block counter. Since each block is 64-byte, a 32-bit word is enough for 256 gigabytes of data. +// Words 13-15 are a nonce, which should not be repeated for the same key. +// For wireguard: "nonce being composed of 32 bits of zeros followed by the 64-bit little-endian value of counter." where counter comes from the Wireguard layer and is separate from the block counter in word 12 +void chacha20_init(struct chacha20_ctx *ctx, const uint8_t *key, const uint64_t nonce) { + ctx->state[0] = CHACHA20_CONSTANT_1; + ctx->state[1] = CHACHA20_CONSTANT_2; + ctx->state[2] = CHACHA20_CONSTANT_3; + ctx->state[3] = CHACHA20_CONSTANT_4; + ctx->state[4] = U8TO32_LITTLE(key + 0); + ctx->state[5] = U8TO32_LITTLE(key + 4); + ctx->state[6] = U8TO32_LITTLE(key + 8); + ctx->state[7] = U8TO32_LITTLE(key + 12); + ctx->state[8] = U8TO32_LITTLE(key + 16); + ctx->state[9] = U8TO32_LITTLE(key + 20); + ctx->state[10] = U8TO32_LITTLE(key + 24); + ctx->state[11] = U8TO32_LITTLE(key + 28); + ctx->state[12] = 0; + ctx->state[13] = 0; + ctx->state[14] = nonce & 0xFFFFFFFF; + ctx->state[15] = nonce >> 32; +} + +// 2.2. HChaCha20 +// HChaCha20 is initialized the same way as the ChaCha cipher, except that HChaCha20 uses a 128-bit nonce and has no counter. +// After initialization, proceed through the ChaCha rounds as usual. +// Once the 20 ChaCha rounds have been completed, the first 128 bits and last 128 bits of the ChaCha state (both little-endian) are concatenated, and this 256-bit subkey is returned. +void hchacha20(uint8_t *out, const uint8_t *nonce, const uint8_t *key) { + uint32_t state[16]; + state[0] = CHACHA20_CONSTANT_1; + state[1] = CHACHA20_CONSTANT_2; + state[2] = CHACHA20_CONSTANT_3; + state[3] = CHACHA20_CONSTANT_4; + state[4] = U8TO32_LITTLE(key + 0); + state[5] = U8TO32_LITTLE(key + 4); + state[6] = U8TO32_LITTLE(key + 8); + state[7] = U8TO32_LITTLE(key + 12); + state[8] = U8TO32_LITTLE(key + 16); + state[9] = U8TO32_LITTLE(key + 20); + state[10] = U8TO32_LITTLE(key + 24); + state[11] = U8TO32_LITTLE(key + 28); + state[12] = U8TO32_LITTLE(nonce + 0); + state[13] = U8TO32_LITTLE(nonce + 4); + state[14] = U8TO32_LITTLE(nonce + 8); + state[15] = U8TO32_LITTLE(nonce + 12); + + TWENTY_ROUNDS(state); + + // Concatenate first/last 128 bits into 256bit output (as little endian) + U32TO8_LITTLE(out + 0, state[0]); + U32TO8_LITTLE(out + 4, state[1]); + U32TO8_LITTLE(out + 8, state[2]); + U32TO8_LITTLE(out + 12, state[3]); + U32TO8_LITTLE(out + 16, state[12]); + U32TO8_LITTLE(out + 20, state[13]); + U32TO8_LITTLE(out + 24, state[14]); + U32TO8_LITTLE(out + 28, state[15]); +} diff --git a/lib/WireGuard-ESP32/src/crypto/refc/chacha20.h b/lib/WireGuard-ESP32/src/crypto/refc/chacha20.h new file mode 100644 index 000000000..aaa802222 --- /dev/null +++ b/lib/WireGuard-ESP32/src/crypto/refc/chacha20.h @@ -0,0 +1,53 @@ +/* + * 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. 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 + */ + +// RFC7539 implementation of ChaCha20 with modified nonce size for WireGuard +// https://tools.ietf.org/html/rfc7539 +// Adapted from https://cr.yp.to/streamciphers/timings/estreambench/submissions/salsa20/chacha8/ref/chacha.c by D. J. Bernstein (Public Domain) +// HChaCha20 is described here: https://tools.ietf.org/id/draft-arciszewski-xchacha-02.html +#ifndef _CHACHA20_H_ +#define _CHACHA20_H_ + +#include + +#define CHACHA20_BLOCK_SIZE (64) +#define CHACHA20_KEY_SIZE (32) + +struct chacha20_ctx { + uint32_t state[16]; +}; + +void chacha20_init(struct chacha20_ctx *ctx, const uint8_t *key, const uint64_t nonce); +void chacha20(struct chacha20_ctx *ctx, uint8_t *out, const uint8_t *in, uint32_t len); +void hchacha20(uint8_t *out, const uint8_t *nonce, const uint8_t *key); + +#endif /* _CHACHA20_H_ */ diff --git a/lib/WireGuard-ESP32/src/crypto/refc/chacha20poly1305.c b/lib/WireGuard-ESP32/src/crypto/refc/chacha20poly1305.c new file mode 100644 index 000000000..972e8b1c1 --- /dev/null +++ b/lib/WireGuard-ESP32/src/crypto/refc/chacha20poly1305.c @@ -0,0 +1,193 @@ +/* + * 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. 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 + */ + +// AEAD_CHACHA20_POLY1305 as described in https://tools.ietf.org/html/rfc7539 +// AEAD_XChaCha20_Poly1305 as described in https://tools.ietf.org/id/draft-arciszewski-xchacha-02.html +#include "chacha20poly1305.h" +#include "chacha20.h" +#include "poly1305-donna.h" + +#include +#include +#include "../../crypto.h" + +#define POLY1305_KEY_SIZE 32 +#define POLY1305_MAC_SIZE 16 + +static const uint8_t zero[CHACHA20_BLOCK_SIZE] = { 0 }; + +// 2.6. Generating the Poly1305 Key Using ChaCha20 +static void generate_poly1305_key(struct poly1305_context *poly1305_state, struct chacha20_ctx *chacha20_state, const uint8_t *key, uint64_t nonce) { + uint8_t block[POLY1305_KEY_SIZE] = {0}; + + // The method is to call the block function with the following parameters: + // - The 256-bit session integrity key is used as the ChaCha20 key. + // - The block counter is set to zero. + // - The protocol will specify a 96-bit or 64-bit nonce + chacha20_init(chacha20_state, key, nonce); + + // We take the first 256 bits or the serialized state, and use those as the one-time Poly1305 key + chacha20(chacha20_state, block, block, sizeof(block)); + + poly1305_init(poly1305_state, block); + + crypto_zero(&block, sizeof(block)); +} + +// 2.8. AEAD Construction (Encryption) +void chacha20poly1305_encrypt(uint8_t *dst, const uint8_t *src, size_t src_len, const uint8_t *ad, size_t ad_len, uint64_t nonce, const uint8_t *key) { + struct poly1305_context poly1305_state; + struct chacha20_ctx chacha20_state; + uint8_t block[8]; + size_t padded_len; + + // First, a Poly1305 one-time key is generated from the 256-bit key and nonce using the procedure described in Section 2.6. + generate_poly1305_key(&poly1305_state, &chacha20_state, key, nonce); + + // Next, the ChaCha20 encryption function is called to encrypt the plaintext, using the same key and nonce, and with the initial counter set to 1. + chacha20(&chacha20_state, dst, src, src_len); + + // Finally, the Poly1305 function is called with the Poly1305 key calculated above, and a message constructed as a concatenation of the following: + // - The AAD + poly1305_update(&poly1305_state, ad, ad_len); + // - padding1 -- the padding is up to 15 zero bytes, and it brings the total length so far to an integral multiple of 16 + padded_len = (ad_len + 15) & 0xFFFFFFF0; // Round up to next 16 bytes + poly1305_update(&poly1305_state, zero, padded_len - ad_len); + // - The ciphertext + poly1305_update(&poly1305_state, dst, src_len); + // - padding2 -- the padding is up to 15 zero bytes, and it brings the total length so far to an integral multiple of 16. + padded_len = (src_len + 15) & 0xFFFFFFF0; // Round up to next 16 bytes + poly1305_update(&poly1305_state, zero, padded_len - src_len); + // - The length of the additional data in octets (as a 64-bit little-endian integer) + U64TO8_LITTLE(block, (uint64_t)ad_len); + poly1305_update(&poly1305_state, block, sizeof(block)); + // - The length of the ciphertext in octets (as a 64-bit little-endian integer). + U64TO8_LITTLE(block, (uint64_t)src_len); + poly1305_update(&poly1305_state, block, sizeof(block)); + + // The output from the AEAD is twofold: + // - A ciphertext of the same length as the plaintext. (above, output of chacha20 into dst) + // - A 128-bit tag, which is the output of the Poly1305 function. (append to dst) + poly1305_finish(&poly1305_state, dst + src_len); + + // Make sure we leave nothing sensitive on the stack + crypto_zero(&chacha20_state, sizeof(chacha20_state)); + crypto_zero(&block, sizeof(block)); +} + +// 2.8. AEAD Construction (Decryption) +bool chacha20poly1305_decrypt(uint8_t *dst, const uint8_t *src, size_t src_len, const uint8_t *ad, size_t ad_len, uint64_t nonce, const uint8_t *key) { + struct poly1305_context poly1305_state; + struct chacha20_ctx chacha20_state; + uint8_t block[8]; + uint8_t mac[POLY1305_MAC_SIZE]; + size_t padded_len; + int dst_len; + bool result = false; + + // Decryption is similar [to encryption] with the following differences: + // - The roles of ciphertext and plaintext are reversed, so the ChaCha20 encryption function is applied to the ciphertext, producing the plaintext. + // - The Poly1305 function is still run on the AAD and the ciphertext, not the plaintext. + // - The calculated tag is bitwise compared to the received tag. The message is authenticated if and only if the tags match. + + if (src_len >= POLY1305_MAC_SIZE) { + dst_len = src_len - POLY1305_MAC_SIZE; + + // First, a Poly1305 one-time key is generated from the 256-bit key and nonce using the procedure described in Section 2.6. + generate_poly1305_key(&poly1305_state, &chacha20_state, key, nonce); + + // Calculate the MAC before attempting decryption + + // the Poly1305 function is called with the Poly1305 key calculated above, and a message constructed as a concatenation of the following: + // - The AAD + poly1305_update(&poly1305_state, ad, ad_len); + // - padding1 -- the padding is up to 15 zero bytes, and it brings the total length so far to an integral multiple of 16 + padded_len = (ad_len + 15) & 0xFFFFFFF0; // Round up to next 16 bytes + poly1305_update(&poly1305_state, zero, padded_len - ad_len); + // - The ciphertext (note the Poly1305 function is still run on the AAD and the ciphertext, not the plaintext) + poly1305_update(&poly1305_state, src, dst_len); + // - padding2 -- the padding is up to 15 zero bytes, and it brings the total length so far to an integral multiple of 16. + padded_len = (dst_len + 15) & 0xFFFFFFF0; // Round up to next 16 bytes + poly1305_update(&poly1305_state, zero, padded_len - dst_len); + // - The length of the additional data in octets (as a 64-bit little-endian integer) + U64TO8_LITTLE(block, (uint64_t)ad_len); + poly1305_update(&poly1305_state, block, sizeof(block)); + // - The length of the ciphertext in octets (as a 64-bit little-endian integer). + U64TO8_LITTLE(block, (uint64_t)dst_len); + poly1305_update(&poly1305_state, block, sizeof(block)); + + // The output from the AEAD is twofold: + // - A plaintext of the same length as the ciphertext. (below, output of chacha20 into dst) + // - A 128-bit tag, which is the output of the Poly1305 function. (into mac for checking against passed mac) + poly1305_finish(&poly1305_state, mac); + + + if (crypto_equal(mac, src + dst_len, POLY1305_MAC_SIZE)) { + // mac is correct - do the decryption + // Next, the ChaCha20 encryption function is called to decrypt the ciphertext, using the same key and nonce, and with the initial counter set to 1. + chacha20(&chacha20_state, dst, src, dst_len); + result = true; + } + } + return result; +} + +// AEAD_XChaCha20_Poly1305 +// XChaCha20-Poly1305 is a variant of the ChaCha20-Poly1305 AEAD construction as defined in [RFC7539] that uses a 192-bit nonce instead of a 96-bit nonce. +// The algorithm for XChaCha20-Poly1305 is as follows: +// 1. Calculate a subkey from the first 16 bytes of the nonce and the key, using HChaCha20 (Section 2.2). +// 2. Use the subkey and remaining 8 bytes of the nonce (prefixed with 4 NUL bytes) with AEAD_CHACHA20_POLY1305 from [RFC7539] as normal. The definition for XChaCha20 is given in Section 2.3. +void xchacha20poly1305_encrypt(uint8_t *dst, const uint8_t *src, size_t src_len, const uint8_t *ad, size_t ad_len, const uint8_t *nonce, const uint8_t *key) { + uint8_t subkey[CHACHA20_KEY_SIZE]; + uint64_t new_nonce; + + new_nonce = U8TO64_LITTLE(nonce + 16); + + hchacha20(subkey, nonce, key); + chacha20poly1305_encrypt(dst, src, src_len, ad, ad_len, new_nonce, subkey); + + crypto_zero(subkey, sizeof(subkey)); +} + +bool xchacha20poly1305_decrypt(uint8_t *dst, const uint8_t *src, size_t src_len, const uint8_t *ad, size_t ad_len, const uint8_t *nonce, const uint8_t *key) { + uint8_t subkey[CHACHA20_KEY_SIZE]; + uint64_t new_nonce; + bool result; + + new_nonce = U8TO64_LITTLE(nonce + 16); + + hchacha20(subkey, nonce, key); + result = chacha20poly1305_decrypt(dst, src, src_len, ad, ad_len, new_nonce, subkey); + + crypto_zero(subkey, sizeof(subkey)); + return result; +} diff --git a/lib/WireGuard-ESP32/src/crypto/refc/chacha20poly1305.h b/lib/WireGuard-ESP32/src/crypto/refc/chacha20poly1305.h new file mode 100644 index 000000000..83fab0727 --- /dev/null +++ b/lib/WireGuard-ESP32/src/crypto/refc/chacha20poly1305.h @@ -0,0 +1,50 @@ +/* + * 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. 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 + */ + +#ifndef _CHACHA20POLY1305_H_ +#define _CHACHA20POLY1305_H_ + +#include +#include +#include + +// Aead(key, counter, plain text, auth text) ChaCha20Poly1305 AEAD, as specified in RFC7539 [17], with its nonce being composed of 32 bits of zeros followed by the 64-bit little-endian value of counter. +// AEAD_CHACHA20_POLY1305 as described in https://tools.ietf.org/html/rfc7539 +void chacha20poly1305_encrypt(uint8_t *dst, const uint8_t *src, size_t src_len, const uint8_t *ad, size_t ad_len, uint64_t nonce, const uint8_t *key); +bool chacha20poly1305_decrypt(uint8_t *dst, const uint8_t *src, size_t src_len, const uint8_t *ad, size_t ad_len, uint64_t nonce, const uint8_t *key); + +// Xaead(key, nonce, plain text, auth text) XChaCha20Poly1305 AEAD, with a 24-byte random nonce, instantiated using HChaCha20 [6] and ChaCha20Poly1305. +// AEAD_XChaCha20_Poly1305 as described in https://tools.ietf.org/id/draft-arciszewski-xchacha-02.html +void xchacha20poly1305_encrypt(uint8_t *dst, const uint8_t *src, size_t src_len, const uint8_t *ad, size_t ad_len, const uint8_t *nonce, const uint8_t *key); +bool xchacha20poly1305_decrypt(uint8_t *dst, const uint8_t *src, size_t src_len, const uint8_t *ad, size_t ad_len, const uint8_t *nonce, const uint8_t *key); + +#endif /* _CHACHA20POLY1305_H_ */ diff --git a/lib/WireGuard-ESP32/src/crypto/refc/poly1305-donna-32.h b/lib/WireGuard-ESP32/src/crypto/refc/poly1305-donna-32.h new file mode 100644 index 000000000..dbcec7740 --- /dev/null +++ b/lib/WireGuard-ESP32/src/crypto/refc/poly1305-donna-32.h @@ -0,0 +1,220 @@ +// Taken from https://github.com/floodyberry/poly1305-donna - public domain or MIT +/* + poly1305 implementation using 32 bit * 32 bit = 64 bit multiplication and 64 bit addition +*/ + +#if defined(_MSC_VER) + #define POLY1305_NOINLINE __declspec(noinline) +#elif defined(__GNUC__) + #define POLY1305_NOINLINE __attribute__((noinline)) +#else + #define POLY1305_NOINLINE +#endif + +#define poly1305_block_size 16 + +/* 17 + sizeof(size_t) + 14*sizeof(unsigned long) */ +typedef struct poly1305_state_internal_t { + unsigned long r[5]; + unsigned long h[5]; + unsigned long pad[4]; + size_t leftover; + unsigned char buffer[poly1305_block_size]; + unsigned char final; +} poly1305_state_internal_t; + +/* interpret four 8 bit unsigned integers as a 32 bit unsigned integer in little endian */ +static unsigned long +U8TO32(const unsigned char *p) { + return + (((unsigned long)(p[0] & 0xff) ) | + ((unsigned long)(p[1] & 0xff) << 8) | + ((unsigned long)(p[2] & 0xff) << 16) | + ((unsigned long)(p[3] & 0xff) << 24)); +} + +/* store a 32 bit unsigned integer as four 8 bit unsigned integers in little endian */ +static void +U32TO8(unsigned char *p, unsigned long v) { + p[0] = (v ) & 0xff; + p[1] = (v >> 8) & 0xff; + p[2] = (v >> 16) & 0xff; + p[3] = (v >> 24) & 0xff; +} + +void +poly1305_init(poly1305_context *ctx, const unsigned char key[32]) { + poly1305_state_internal_t *st = (poly1305_state_internal_t *)ctx; + + /* r &= 0xffffffc0ffffffc0ffffffc0fffffff */ + st->r[0] = (U8TO32(&key[ 0]) ) & 0x3ffffff; + st->r[1] = (U8TO32(&key[ 3]) >> 2) & 0x3ffff03; + st->r[2] = (U8TO32(&key[ 6]) >> 4) & 0x3ffc0ff; + st->r[3] = (U8TO32(&key[ 9]) >> 6) & 0x3f03fff; + st->r[4] = (U8TO32(&key[12]) >> 8) & 0x00fffff; + + /* h = 0 */ + st->h[0] = 0; + st->h[1] = 0; + st->h[2] = 0; + st->h[3] = 0; + st->h[4] = 0; + + /* save pad for later */ + st->pad[0] = U8TO32(&key[16]); + st->pad[1] = U8TO32(&key[20]); + st->pad[2] = U8TO32(&key[24]); + st->pad[3] = U8TO32(&key[28]); + + st->leftover = 0; + st->final = 0; +} + +static void +poly1305_blocks(poly1305_state_internal_t *st, const unsigned char *m, size_t bytes) { + const unsigned long hibit = (st->final) ? 0 : (1UL << 24); /* 1 << 128 */ + unsigned long r0,r1,r2,r3,r4; + unsigned long s1,s2,s3,s4; + unsigned long h0,h1,h2,h3,h4; + unsigned long long d0,d1,d2,d3,d4; + unsigned long c; + + r0 = st->r[0]; + r1 = st->r[1]; + r2 = st->r[2]; + r3 = st->r[3]; + r4 = st->r[4]; + + s1 = r1 * 5; + s2 = r2 * 5; + s3 = r3 * 5; + s4 = r4 * 5; + + h0 = st->h[0]; + h1 = st->h[1]; + h2 = st->h[2]; + h3 = st->h[3]; + h4 = st->h[4]; + + while (bytes >= poly1305_block_size) { + /* h += m[i] */ + h0 += (U8TO32(m+ 0) ) & 0x3ffffff; + h1 += (U8TO32(m+ 3) >> 2) & 0x3ffffff; + h2 += (U8TO32(m+ 6) >> 4) & 0x3ffffff; + h3 += (U8TO32(m+ 9) >> 6) & 0x3ffffff; + h4 += (U8TO32(m+12) >> 8) | hibit; + + /* h *= r */ + d0 = ((unsigned long long)h0 * r0) + ((unsigned long long)h1 * s4) + ((unsigned long long)h2 * s3) + ((unsigned long long)h3 * s2) + ((unsigned long long)h4 * s1); + d1 = ((unsigned long long)h0 * r1) + ((unsigned long long)h1 * r0) + ((unsigned long long)h2 * s4) + ((unsigned long long)h3 * s3) + ((unsigned long long)h4 * s2); + d2 = ((unsigned long long)h0 * r2) + ((unsigned long long)h1 * r1) + ((unsigned long long)h2 * r0) + ((unsigned long long)h3 * s4) + ((unsigned long long)h4 * s3); + d3 = ((unsigned long long)h0 * r3) + ((unsigned long long)h1 * r2) + ((unsigned long long)h2 * r1) + ((unsigned long long)h3 * r0) + ((unsigned long long)h4 * s4); + d4 = ((unsigned long long)h0 * r4) + ((unsigned long long)h1 * r3) + ((unsigned long long)h2 * r2) + ((unsigned long long)h3 * r1) + ((unsigned long long)h4 * r0); + + /* (partial) h %= p */ + c = (unsigned long)(d0 >> 26); h0 = (unsigned long)d0 & 0x3ffffff; + d1 += c; c = (unsigned long)(d1 >> 26); h1 = (unsigned long)d1 & 0x3ffffff; + d2 += c; c = (unsigned long)(d2 >> 26); h2 = (unsigned long)d2 & 0x3ffffff; + d3 += c; c = (unsigned long)(d3 >> 26); h3 = (unsigned long)d3 & 0x3ffffff; + d4 += c; c = (unsigned long)(d4 >> 26); h4 = (unsigned long)d4 & 0x3ffffff; + h0 += c * 5; c = (h0 >> 26); h0 = h0 & 0x3ffffff; + h1 += c; + + m += poly1305_block_size; + bytes -= poly1305_block_size; + } + + st->h[0] = h0; + st->h[1] = h1; + st->h[2] = h2; + st->h[3] = h3; + st->h[4] = h4; +} + +POLY1305_NOINLINE void +poly1305_finish(poly1305_context *ctx, unsigned char mac[16]) { + poly1305_state_internal_t *st = (poly1305_state_internal_t *)ctx; + unsigned long h0,h1,h2,h3,h4,c; + unsigned long g0,g1,g2,g3,g4; + unsigned long long f; + unsigned long mask; + + /* process the remaining block */ + if (st->leftover) { + size_t i = st->leftover; + st->buffer[i++] = 1; + for (; i < poly1305_block_size; i++) + st->buffer[i] = 0; + st->final = 1; + poly1305_blocks(st, st->buffer, poly1305_block_size); + } + + /* fully carry h */ + h0 = st->h[0]; + h1 = st->h[1]; + h2 = st->h[2]; + h3 = st->h[3]; + h4 = st->h[4]; + + c = h1 >> 26; h1 = h1 & 0x3ffffff; + h2 += c; c = h2 >> 26; h2 = h2 & 0x3ffffff; + h3 += c; c = h3 >> 26; h3 = h3 & 0x3ffffff; + h4 += c; c = h4 >> 26; h4 = h4 & 0x3ffffff; + h0 += c * 5; c = h0 >> 26; h0 = h0 & 0x3ffffff; + h1 += c; + + /* compute h + -p */ + g0 = h0 + 5; c = g0 >> 26; g0 &= 0x3ffffff; + g1 = h1 + c; c = g1 >> 26; g1 &= 0x3ffffff; + g2 = h2 + c; c = g2 >> 26; g2 &= 0x3ffffff; + g3 = h3 + c; c = g3 >> 26; g3 &= 0x3ffffff; + g4 = h4 + c - (1UL << 26); + + /* select h if h < p, or h + -p if h >= p */ + mask = (g4 >> ((sizeof(unsigned long) * 8) - 1)) - 1; + g0 &= mask; + g1 &= mask; + g2 &= mask; + g3 &= mask; + g4 &= mask; + mask = ~mask; + h0 = (h0 & mask) | g0; + h1 = (h1 & mask) | g1; + h2 = (h2 & mask) | g2; + h3 = (h3 & mask) | g3; + h4 = (h4 & mask) | g4; + + /* h = h % (2^128) */ + h0 = ((h0 ) | (h1 << 26)) & 0xffffffff; + h1 = ((h1 >> 6) | (h2 << 20)) & 0xffffffff; + h2 = ((h2 >> 12) | (h3 << 14)) & 0xffffffff; + h3 = ((h3 >> 18) | (h4 << 8)) & 0xffffffff; + + /* mac = (h + pad) % (2^128) */ + f = (unsigned long long)h0 + st->pad[0] ; h0 = (unsigned long)f; + f = (unsigned long long)h1 + st->pad[1] + (f >> 32); h1 = (unsigned long)f; + f = (unsigned long long)h2 + st->pad[2] + (f >> 32); h2 = (unsigned long)f; + f = (unsigned long long)h3 + st->pad[3] + (f >> 32); h3 = (unsigned long)f; + + U32TO8(mac + 0, h0); + U32TO8(mac + 4, h1); + U32TO8(mac + 8, h2); + U32TO8(mac + 12, h3); + + /* zero out the state */ + st->h[0] = 0; + st->h[1] = 0; + st->h[2] = 0; + st->h[3] = 0; + st->h[4] = 0; + st->r[0] = 0; + st->r[1] = 0; + st->r[2] = 0; + st->r[3] = 0; + st->r[4] = 0; + st->pad[0] = 0; + st->pad[1] = 0; + st->pad[2] = 0; + st->pad[3] = 0; +} + diff --git a/lib/WireGuard-ESP32/src/crypto/refc/poly1305-donna.c b/lib/WireGuard-ESP32/src/crypto/refc/poly1305-donna.c new file mode 100644 index 000000000..31ad7c597 --- /dev/null +++ b/lib/WireGuard-ESP32/src/crypto/refc/poly1305-donna.c @@ -0,0 +1,41 @@ +// Taken from https://github.com/floodyberry/poly1305-donna - public domain or MIT + +#include "poly1305-donna.h" +#include "poly1305-donna-32.h" + +void +poly1305_update(poly1305_context *ctx, const unsigned char *m, size_t bytes) { + poly1305_state_internal_t *st = (poly1305_state_internal_t *)ctx; + size_t i; + + /* handle leftover */ + if (st->leftover) { + size_t want = (poly1305_block_size - st->leftover); + if (want > bytes) + want = bytes; + for (i = 0; i < want; i++) + st->buffer[st->leftover + i] = m[i]; + bytes -= want; + m += want; + st->leftover += want; + if (st->leftover < poly1305_block_size) + return; + poly1305_blocks(st, st->buffer, poly1305_block_size); + st->leftover = 0; + } + + /* process full blocks */ + if (bytes >= poly1305_block_size) { + size_t want = (bytes & ~(poly1305_block_size - 1)); + poly1305_blocks(st, m, want); + m += want; + bytes -= want; + } + + /* store leftover */ + if (bytes) { + for (i = 0; i < bytes; i++) + st->buffer[st->leftover + i] = m[i]; + st->leftover += bytes; + } +} diff --git a/lib/WireGuard-ESP32/src/crypto/refc/poly1305-donna.h b/lib/WireGuard-ESP32/src/crypto/refc/poly1305-donna.h new file mode 100644 index 000000000..955bca991 --- /dev/null +++ b/lib/WireGuard-ESP32/src/crypto/refc/poly1305-donna.h @@ -0,0 +1,16 @@ +// Taken from https://github.com/floodyberry/poly1305-donna - public domain or MIT +#ifndef POLY1305_DONNA_H +#define POLY1305_DONNA_H + +#include + +typedef struct poly1305_context { + size_t aligner; + unsigned char opaque[136]; +} poly1305_context; + +void poly1305_init(poly1305_context *ctx, const unsigned char key[32]); +void poly1305_update(poly1305_context *ctx, const unsigned char *m, size_t bytes); +void poly1305_finish(poly1305_context *ctx, unsigned char mac[16]); + +#endif /* POLY1305_DONNA_H */ diff --git a/lib/WireGuard-ESP32/src/crypto/refc/x25519-license.txt b/lib/WireGuard-ESP32/src/crypto/refc/x25519-license.txt new file mode 100644 index 000000000..81e486211 --- /dev/null +++ b/lib/WireGuard-ESP32/src/crypto/refc/x25519-license.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015-2016 Cryptography Research, Inc. + +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: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +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. diff --git a/lib/WireGuard-ESP32/src/crypto/refc/x25519.c b/lib/WireGuard-ESP32/src/crypto/refc/x25519.c new file mode 100644 index 000000000..3b5ebe366 --- /dev/null +++ b/lib/WireGuard-ESP32/src/crypto/refc/x25519.c @@ -0,0 +1,448 @@ +// Taken from https://sourceforge.net/p/strobe (MIT Licence) +/** + * @cond internal + * @file x25519.c + * @copyright + * Copyright (c) 2015-2016 Cryptography Research, Inc. \n + * Released under the MIT License. See LICENSE.txt for license information. + * @author Mike Hamburg + * @brief Key exchange and signatures based on X25519. + */ +#include +#include "x25519.h" +//#include "strobe.h" +//#include "strobe_config.h" +// STROBE header replacement +#include +#define X25519_WBITS 32 +#define X25519_SUPPORT_SIGN 0 +#define X25519_MEMCPY_PARAMS 1 +#define X25519_USE_POWER_CHAIN 1 +#if BYTE_ORDER == LITTLE_ENDIAN +static inline uint32_t eswap_letoh_32(uint32_t w) { return w; } +#else +#error "Fix eswap() on non-little-endian machine" +#endif + +#if X25519_WBITS == 64 + typedef uint64_t limb_t; + typedef __uint128_t dlimb_t; + typedef __int128_t sdlimb_t; + #define eswap_limb eswap_letoh_64 + #define LIMB(x) x##ull +#elif X25519_WBITS == 32 + typedef uint32_t limb_t; + typedef uint64_t dlimb_t; + typedef int64_t sdlimb_t; + #define eswap_limb eswap_letoh_32 + #define LIMB(x) (uint32_t)(x##ull),(uint32_t)((x##ull)>>32) +#else + #error "Need to know X25519_WBITS" +#endif + +#define NLIMBS (256/X25519_WBITS) +typedef limb_t fe[NLIMBS]; + +#if X25519_SUPPORT_SIGN +typedef limb_t scalar_t[NLIMBS]; +static const limb_t MONTGOMERY_FACTOR = (limb_t)0xd2b51da312547e1bull; +static const scalar_t sc_p = { + LIMB(0x5812631a5cf5d3ed), LIMB(0x14def9dea2f79cd6), + LIMB(0x0000000000000000), LIMB(0x1000000000000000) +}, sc_r2 = { + LIMB(0xa40611e3449c0f01), LIMB(0xd00e1ba768859347), + LIMB(0xceec73d217f5be65), LIMB(0x0399411b7c309a3d) +}; +#endif + +static inline limb_t umaal( + limb_t *carry, limb_t acc, limb_t mand, limb_t mier +) { + dlimb_t tmp = (dlimb_t) mand * mier + acc + *carry; + *carry = tmp >> X25519_WBITS; + return tmp; +} + +/* These functions are implemented in terms of umaal on ARM */ +static inline limb_t adc(limb_t *carry, limb_t acc, limb_t mand) { + dlimb_t total = (dlimb_t)*carry + acc + mand; + *carry = total>>X25519_WBITS; + return total; +} + +static inline limb_t adc0(limb_t *carry, limb_t acc) { + dlimb_t total = (dlimb_t)*carry + acc; + *carry = total>>X25519_WBITS; + return total; +} + +/* Precondition: carry is small. + * Invariant: result of propagate is < 2^255 + 1 word + * In particular, always less than 2p. + * Also, output x >= min(x,19) + */ +static void propagate(fe x, limb_t over) { + unsigned i; + over = x[NLIMBS-1]>>(X25519_WBITS-1) | over<<1; + x[NLIMBS-1] &= ~((limb_t)1<<(X25519_WBITS-1)); + + limb_t carry = over * 19; + for (i=0; i>= X25519_WBITS; + } + propagate(out,1+carry); +} + +static void __attribute__((unused)) +swapin(limb_t *x, const uint8_t *in) { + memcpy(x,in,sizeof(fe)); + unsigned i; + for (i=0; i>= X25519_WBITS; + } + return ((dlimb_t)res - 1) >> X25519_WBITS; +} + +static const limb_t a24[1]={121665}; + +static void ladder_part1(fe xs[5]) { + limb_t *x2 = xs[0], *z2=xs[1],*x3=xs[2],*z3=xs[3],*t1=xs[4]; + add(t1,x2,z2); // t1 = A + sub(z2,x2,z2); // z2 = B + add(x2,x3,z3); // x2 = C + sub(z3,x3,z3); // z3 = D + mul1(z3,t1); // z3 = DA + mul1(x2,z2); // x3 = BC + add(x3,z3,x2); // x3 = DA+CB + sub(z3,z3,x2); // z3 = DA-CB + sqr1(t1); // t1 = AA + sqr1(z2); // z2 = BB + sub(x2,t1,z2); // x2 = E = AA-BB + mul(z2,x2,a24,sizeof(a24)/sizeof(a24[0])); // z2 = E*a24 + add(z2,z2,t1); // z2 = E*a24 + AA +} +static void ladder_part2(fe xs[5], const fe x1) { + limb_t *x2 = xs[0], *z2=xs[1],*x3=xs[2],*z3=xs[3],*t1=xs[4]; + sqr1(z3); // z3 = (DA-CB)^2 + mul1(z3,x1); // z3 = x1 * (DA-CB)^2 + sqr1(x3); // x3 = (DA+CB)^2 + mul1(z2,x2); // z2 = AA*(E*a24+AA) + sub(x2,t1,x2); // x2 = BB again + mul1(x2,t1); // x2 = AA*BB +} + +static void x25519_core(fe xs[5], const uint8_t scalar[X25519_BYTES], const uint8_t *x1, int clamp) { + int i; +#if X25519_MEMCPY_PARAMS + fe x1i; + swapin(x1i,x1); + x1 = (const uint8_t *)x1; +#endif + limb_t swap = 0; + limb_t *x2 = xs[0],*x3=xs[2],*z3=xs[3]; + memset(xs,0,4*sizeof(fe)); + x2[0] = z3[0] = 1; + memcpy(x3,x1,sizeof(fe)); + + for (i=255; i>=0; i--) { + uint8_t bytei = scalar[i/8]; + if (clamp) { + if (i/8 == 0) { + bytei &= ~7; + } else if (i/8 == X25519_BYTES-1) { + bytei &= 0x7F; + bytei |= 0x40; + } + } + limb_t doswap = -(limb_t)((bytei>>(i%8)) & 1); + condswap(x2,x3,swap^doswap); + swap = doswap; + + ladder_part1(xs); + ladder_part2(xs,(const limb_t *)x1); + } + condswap(x2,x3,swap); +} + +int x25519(uint8_t out[X25519_BYTES], const uint8_t scalar[X25519_BYTES], const uint8_t x1[X25519_BYTES], int clamp) { + fe xs[5]; + x25519_core(xs,scalar,x1,clamp); + + /* Precomputed inversion chain */ + limb_t *x2 = xs[0], *z2=xs[1], *z3=xs[3]; + int i; + + limb_t *prev = z2; +#if X25519_USE_POWER_CHAIN + static const struct { uint8_t a,c,n; } steps[13] = { + {2,1,1 }, + {2,1,1 }, + {4,2,3 }, + {2,4,6 }, + {3,1,1 }, + {3,2,12 }, + {4,3,25 }, + {2,3,25 }, + {2,4,50 }, + {3,2,125}, + {3,1,2 }, + {3,1,2 }, + {3,1,1 } + }; + for (i=0; i<13; i++) { + int j; + limb_t *a = xs[steps[i].a]; + for (j=steps[i].n; j>0; j--) { + sqr(a, prev); + prev = a; + } + mul1(a,xs[steps[i].c]); + } +#else + /* Raise to the p-2 = 0x7f..ffeb */ + for (i=253; i>=0; i--) { + sqr(z3,prev); + prev = z3; + if (i>=8 || (0xeb>>i & 1)) { + mul1(z3,z2); + } + } +#endif + + /* Here prev = z3 */ + /* x2 /= z2 */ +#if X25519_MEMCPY_PARAMS + mul1(x2,z3); + int ret = canon(x2); + swapout(out,x2); +#else + mul((limb_t *)out, x2, z3, NLIMBS); + int ret = canon((limb_t*)out); +#endif + if (clamp) return ret; + else return 0; +} + +const uint8_t X25519_BASE_POINT[X25519_BYTES] = {9}; + +#if X25519_SUPPORT_VERIFY +static limb_t x25519_verify_core( + fe xs[5], + const limb_t *other1, + const uint8_t other2[X25519_BYTES] +) { + limb_t *z2=xs[1],*x3=xs[2],*z3=xs[3]; +#if X25519_MEMCPY_PARAMS + fe xo2; + swapin(xo2,other2); +#else + const limb_t *xo2 = (const limb_t *)other2; +#endif + + memcpy(x3, other1, 2*sizeof(fe)); + + ladder_part1(xs); + + /* Here z2 = t2^2 */ + mul1(z2,other1); + mul1(z2,other1+NLIMBS); + mul1(z2,xo2); + const limb_t sixteen = 16; + mul (z2,z2,&sixteen,1); + + mul1(z3,xo2); + sub(z3,z3,x3); + sqr1(z3); + + /* check equality */ + sub(z3,z3,z2); + + /* If canon(z2) then both sides are zero. + * If canon(z3) then the two sides are equal. + * + * Reject sigs where both sides are zero, because + * that can happen if an input causes the ladder to + * return 0/0. + */ + return canon(z2) | ~canon(z3); +} + +int x25519_verify_p2 ( + const uint8_t response[X25519_BYTES], + const uint8_t challenge[X25519_BYTES], + const uint8_t eph[X25519_BYTES], + const uint8_t pub[X25519_BYTES] +) { + fe xs[7]; + x25519_core(&xs[0],challenge,pub,0); + x25519_core(&xs[2],response,X25519_BASE_POINT,0); + return x25519_verify_core(&xs[2],xs[0],eph); +} +#endif // X25519_SUPPORT_VERIFY + +#if X25519_SUPPORT_SIGN +static void sc_montmul ( + scalar_t out, + const scalar_t a, + const scalar_t b +) { + /** + * OK, so carry bounding. We're using a high carry, so that the + * inputs don't have to be reduced. + * + * First montmul: output < (M^2 + Mp)/M = M+p, subtract p, < M. This gets rid of high carry. + * Second montmul, by r^2 mod p < p: output < (Mp + Mp)/M = 2p, subtract p, < p, done. + */ + unsigned i,j; + limb_t hic = 0; + for (i=0; i0) out[j-1] = acc; + } + + /* Add two carry registers and high carry */ + out[NLIMBS-1] = adc(&hic, carry, carry2); + } + + /* Reduce */ + sdlimb_t scarry = 0; + for (i=0; i>= X25519_WBITS; + } + limb_t need_add = -(scarry + hic); + + limb_t carry = 0; + for (i=0; i +#include "crypto.h" +#include "lwip/sys.h" +#include "mbedtls/entropy.h" +#include "mbedtls/ctr_drbg.h" +#include "esp_system.h" + +static struct mbedtls_ctr_drbg_context random_context; +static struct mbedtls_entropy_context entropy_context; +static bool is_platform_initialized = false; + +static int entropy_hw_random_source( void *data, unsigned char *output, size_t len, size_t *olen ) { + esp_fill_random(output, len); + *olen = len; + return 0; +} + +void wireguard_platform_init() { + if( is_platform_initialized ) return; + + mbedtls_entropy_init(&entropy_context); + mbedtls_ctr_drbg_init(&random_context); + mbedtls_entropy_add_source(&entropy_context, entropy_hw_random_source, NULL, 134, MBEDTLS_ENTROPY_SOURCE_STRONG); + mbedtls_ctr_drbg_seed(&random_context, mbedtls_entropy_func, &entropy_context, NULL, 0); + + is_platform_initialized = true; +} + +void wireguard_random_bytes(void *bytes, size_t size) { + uint8_t *out = (uint8_t *)bytes; + mbedtls_ctr_drbg_random(&random_context, bytes, size); +} + +uint32_t wireguard_sys_now() { + // Default to the LwIP system time + return sys_now(); +} + +void wireguard_tai64n_now(uint8_t *output) { + // See https://cr.yp.to/libtai/tai64.html + // 64 bit seconds from 1970 = 8 bytes + // 32 bit nano seconds from current second + + // Get timestamp. Note that the timestamp must be synced by NTP, + // or at least preserved in NVS, not to go back after reset. + // Otherwise, the WireGuard remote peer rejects handshake. + struct timeval tv; + gettimeofday(&tv, NULL); + uint64_t millis = (tv.tv_sec * 1000LL + (tv.tv_usec / 1000LL)); + + // Split into seconds offset + nanos + uint64_t seconds = 0x400000000000000aULL + (millis / 1000); + uint32_t nanos = (millis % 1000) * 1000; + U64TO8_BIG(output + 0, seconds); + U32TO8_BIG(output + 8, nanos); +} + +bool wireguard_is_under_load() { + return false; +} + diff --git a/lib/WireGuard-ESP32/src/wireguard-platform.h b/lib/WireGuard-ESP32/src/wireguard-platform.h new file mode 100644 index 000000000..f54ec4a96 --- /dev/null +++ b/lib/WireGuard-ESP32/src/wireguard-platform.h @@ -0,0 +1,71 @@ +/* + * Ported to ESP32 Arduino by Kenta Ida (fuga@fugafuga.org) + * The original license is below: + * + * 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. 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 + */ + +#ifndef _WIREGUARD_PLATFORM_H_ +#define _WIREGUARD_PLATFORM_H_ + +#include +#include +#include + +// Peers are allocated statically inside the device structure to avoid malloc +#define WIREGUARD_MAX_PEERS 1 +#define WIREGUARD_MAX_SRC_IPS 2 + +// Per device limit on accepting (valid) initiation requests - per peer +#define MAX_INITIATIONS_PER_SECOND (2) + +// +// Your platform integration needs to provide implementations of these functions +// + +void wireguard_platform_init(); + +// The number of milliseconds since system boot - for LwIP systems this could be sys_now() +uint32_t wireguard_sys_now(); + +// Fill the supplied buffer with random data - random data is used for generating new session keys periodically +void wireguard_random_bytes(void *bytes, size_t size); + +// Get the current time in tai64n format - 8 byte seconds, 4 byte nano sub-second - see https://cr.yp.to/libtai/tai64.html for details +// Output buffer passed is 12 bytes +// The Wireguard implementation doesn't strictly need this to be a time, but instead an increasing value +// The remote end of the Wireguard tunnel will use this value in handshake replay detection +void wireguard_tai64n_now(uint8_t *output); + +// Is the system under load - i.e. should we generate cookie reply message in response to initiation messages +bool wireguard_is_under_load(); + +#endif /* _WIREGUARD_PLATFORM_H_ */ diff --git a/lib/WireGuard-ESP32/src/wireguard.c b/lib/WireGuard-ESP32/src/wireguard.c new file mode 100644 index 000000000..ca86e9beb --- /dev/null +++ b/lib/WireGuard-ESP32/src/wireguard.c @@ -0,0 +1,1129 @@ +/* + * Ported to ESP32 Arduino by Kenta Ida (fuga@fugafuga.org) + * The original license is below: + * + * 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. 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 + */ + +#include "wireguard.h" + +#include +#include +#include + +#include "crypto.h" + +// For HMAC calculation +#define WIREGUARD_BLAKE2S_BLOCK_SIZE (64) + +// 5.4 Messages +// Constants +static const uint8_t CONSTRUCTION[37] = "Noise_IKpsk2_25519_ChaChaPoly_BLAKE2s"; // The UTF-8 string literal "Noise_IKpsk2_25519_ChaChaPoly_BLAKE2s", 37 bytes of output +static const uint8_t IDENTIFIER[34] = "WireGuard v1 zx2c4 Jason@zx2c4.com"; // The UTF-8 string literal "WireGuard v1 zx2c4 Jason@zx2c4.com", 34 bytes of output +static const uint8_t LABEL_MAC1[8] = "mac1----"; // Label-Mac1 The UTF-8 string literal "mac1----", 8 bytes of output. +static const uint8_t LABEL_COOKIE[8] = "cookie--"; // Label-Cookie The UTF-8 string literal "cookie--", 8 bytes of output + +static const char *base64_lookup = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +static const uint8_t zero_key[WIREGUARD_PUBLIC_KEY_LEN] = { 0 }; + +// Calculated in wireguard_init +static uint8_t construction_hash[WIREGUARD_HASH_LEN]; +static uint8_t identifier_hash[WIREGUARD_HASH_LEN]; + + +void wireguard_init() { + wireguard_blake2s_ctx ctx; + // Pre-calculate chaining key hash + wireguard_blake2s_init(&ctx, WIREGUARD_HASH_LEN, NULL, 0); + wireguard_blake2s_update(&ctx, CONSTRUCTION, sizeof(CONSTRUCTION)); + wireguard_blake2s_final(&ctx, construction_hash); + // Pre-calculate initial handshake hash - uses construction_hash calculated above + wireguard_blake2s_init(&ctx, WIREGUARD_HASH_LEN, NULL, 0); + wireguard_blake2s_update(&ctx, construction_hash, sizeof(construction_hash)); + wireguard_blake2s_update(&ctx, IDENTIFIER, sizeof(IDENTIFIER)); + wireguard_blake2s_final(&ctx, identifier_hash); +} + +struct wireguard_peer *peer_alloc(struct wireguard_device *device) { + struct wireguard_peer *result = NULL; + struct wireguard_peer *tmp; + int x; + for (x=0; x < WIREGUARD_MAX_PEERS; x++) { + tmp = &device->peers[x]; + if (!tmp->valid) { + result = tmp; + break; + } + } + return result; +} + +struct wireguard_peer *peer_lookup_by_pubkey(struct wireguard_device *device, uint8_t *public_key) { + struct wireguard_peer *result = NULL; + struct wireguard_peer *tmp; + int x; + for (x=0; x < WIREGUARD_MAX_PEERS; x++) { + tmp = &device->peers[x]; + if (tmp->valid) { + if (memcmp(tmp->public_key, public_key, WIREGUARD_PUBLIC_KEY_LEN) == 0) { + result = tmp; + break; + } + } + } + return result; +} + +uint8_t wireguard_peer_index(struct wireguard_device *device, struct wireguard_peer *peer) { + uint8_t result = 0xFF; + uint8_t x; + for (x=0; x < WIREGUARD_MAX_PEERS; x++) { + if (peer == &device->peers[x]) { + result = x; + break; + } + } + return result; +} + +struct wireguard_peer *peer_lookup_by_peer_index(struct wireguard_device *device, uint8_t peer_index) { + struct wireguard_peer *result = NULL; + if (peer_index < WIREGUARD_MAX_PEERS) { + if (device->peers[peer_index].valid) { + result = &device->peers[peer_index]; + } + } + return result; +} + +struct wireguard_peer *peer_lookup_by_receiver(struct wireguard_device *device, uint32_t receiver) { + struct wireguard_peer *result = NULL; + struct wireguard_peer *tmp; + int x; + for (x=0; x < WIREGUARD_MAX_PEERS; x++) { + tmp = &device->peers[x]; + if (tmp->valid) { + if ((tmp->curr_keypair.valid && (tmp->curr_keypair.local_index == receiver)) || + (tmp->next_keypair.valid && (tmp->next_keypair.local_index == receiver)) || + (tmp->prev_keypair.valid && (tmp->prev_keypair.local_index == receiver)) + ) { + result = tmp; + break; + } + } + } + return result; +} + +struct wireguard_peer *peer_lookup_by_handshake(struct wireguard_device *device, uint32_t receiver) { + struct wireguard_peer *result = NULL; + struct wireguard_peer *tmp; + int x; + for (x=0; x < WIREGUARD_MAX_PEERS; x++) { + tmp = &device->peers[x]; + if (tmp->valid) { + if (tmp->handshake.valid && tmp->handshake.initiator && (tmp->handshake.local_index == receiver)) { + result = tmp; + break; + } + } + } + return result; +} + +bool wireguard_expired(uint32_t created_millis, uint32_t valid_seconds) { + uint32_t diff = wireguard_sys_now() - created_millis; + return (diff >= (valid_seconds * 1000)); +} + + +static void generate_cookie_secret(struct wireguard_device *device) { + wireguard_random_bytes(device->cookie_secret, WIREGUARD_HASH_LEN); + device->cookie_secret_millis = wireguard_sys_now(); +} + +static void generate_peer_cookie(struct wireguard_device *device, uint8_t *cookie, uint8_t *source_addr_port, size_t source_length) { + wireguard_blake2s_ctx ctx; + + if (wireguard_expired(device->cookie_secret_millis, COOKIE_SECRET_MAX_AGE)) { + // Generate new random bytes + generate_cookie_secret(device); + } + + // Mac(key, input) Keyed-Blake2s(key, input, 16), the keyed MAC variant of the BLAKE2s hash function, returning 16 bytes of output + wireguard_blake2s_init(&ctx, WIREGUARD_COOKIE_LEN, device->cookie_secret, WIREGUARD_HASH_LEN); + // 5.4.7 Under Load: Cookie Reply Message + // Mix in the IP address and port - have the IP layer pass this in as byte array to avoid using Lwip specific APIs in this module + if ((source_addr_port) && (source_length > 0)) { + wireguard_blake2s_update(&ctx, source_addr_port, source_length); + } + wireguard_blake2s_final(&ctx, cookie); +} + +static void wireguard_mac(uint8_t *dst, const void *message, size_t len, const uint8_t *key, size_t keylen) { + wireguard_blake2s(dst, WIREGUARD_COOKIE_LEN, key, keylen, message, len); +} + +static void wireguard_mac_key(uint8_t *key, const uint8_t *public_key, const uint8_t *label, size_t label_len) { + blake2s_ctx ctx; + blake2s_init(&ctx, WIREGUARD_SESSION_KEY_LEN, NULL, 0); + blake2s_update(&ctx, label, label_len); + blake2s_update(&ctx, public_key, WIREGUARD_PUBLIC_KEY_LEN); + blake2s_final(&ctx, key); +} + +static void wireguard_mix_hash(uint8_t *hash, const uint8_t *src, size_t src_len) { + wireguard_blake2s_ctx ctx; + wireguard_blake2s_init(&ctx, WIREGUARD_HASH_LEN, NULL, 0); + wireguard_blake2s_update(&ctx, hash, WIREGUARD_HASH_LEN); + wireguard_blake2s_update(&ctx, src, src_len); + wireguard_blake2s_final(&ctx, hash); +} + +static void wireguard_hmac(uint8_t *digest, const uint8_t *key, size_t key_len, const uint8_t *text, size_t text_len) { + // Adapted from appendix example in RFC2104 to use BLAKE2S instead of MD5 - https://tools.ietf.org/html/rfc2104 + wireguard_blake2s_ctx ctx; + uint8_t k_ipad[WIREGUARD_BLAKE2S_BLOCK_SIZE]; // inner padding - key XORd with ipad + uint8_t k_opad[WIREGUARD_BLAKE2S_BLOCK_SIZE]; // outer padding - key XORd with opad + + uint8_t tk[WIREGUARD_HASH_LEN]; + int i; + // if key is longer than BLAKE2S_BLOCK_SIZE bytes reset it to key=BLAKE2S(key) + if (key_len > WIREGUARD_BLAKE2S_BLOCK_SIZE) { + wireguard_blake2s_ctx tctx; + wireguard_blake2s_init(&tctx, WIREGUARD_HASH_LEN, NULL, 0); + wireguard_blake2s_update(&tctx, key, key_len); + wireguard_blake2s_final(&tctx, tk); + key = tk; + key_len = WIREGUARD_HASH_LEN; + } + + // the HMAC transform looks like: + // HASH(K XOR opad, HASH(K XOR ipad, text)) + // where K is an n byte key + // ipad is the byte 0x36 repeated BLAKE2S_BLOCK_SIZE times + // opad is the byte 0x5c repeated BLAKE2S_BLOCK_SIZE times + // and text is the data being protected + memset(k_ipad, 0, sizeof(k_ipad)); + memset(k_opad, 0, sizeof(k_opad)); + memcpy(k_ipad, key, key_len); + memcpy(k_opad, key, key_len); + + // XOR key with ipad and opad values + for (i=0; i < WIREGUARD_BLAKE2S_BLOCK_SIZE; i++) { + k_ipad[i] ^= 0x36; + k_opad[i] ^= 0x5c; + } + // perform inner HASH + wireguard_blake2s_init(&ctx, WIREGUARD_HASH_LEN, NULL, 0); // init context for 1st pass + wireguard_blake2s_update(&ctx, k_ipad, WIREGUARD_BLAKE2S_BLOCK_SIZE); // start with inner pad + wireguard_blake2s_update(&ctx, text, text_len); // then text of datagram + wireguard_blake2s_final(&ctx, digest); // finish up 1st pass + + // perform outer HASH + wireguard_blake2s_init(&ctx, WIREGUARD_HASH_LEN, NULL, 0); // init context for 2nd pass + wireguard_blake2s_update(&ctx, k_opad, WIREGUARD_BLAKE2S_BLOCK_SIZE); // start with outer pad + wireguard_blake2s_update(&ctx, digest, WIREGUARD_HASH_LEN); // then results of 1st hash + wireguard_blake2s_final(&ctx, digest); // finish up 2nd pass +} + +static void wireguard_kdf1(uint8_t *tau1, const uint8_t *chaining_key, const uint8_t *data, size_t data_len) { + uint8_t tau0[WIREGUARD_HASH_LEN]; + uint8_t output[WIREGUARD_HASH_LEN + 1]; + + // tau0 = Hmac(key, input) + wireguard_hmac(tau0, chaining_key, WIREGUARD_HASH_LEN, data, data_len); + // tau1 := Hmac(tau0, 0x1) + output[0] = 1; + wireguard_hmac(output, tau0, WIREGUARD_HASH_LEN, output, 1); + memcpy(tau1, output, WIREGUARD_HASH_LEN); + + // Wipe intermediates + crypto_zero(tau0, sizeof(tau0)); + crypto_zero(output, sizeof(output)); +} + +static void wireguard_kdf2(uint8_t *tau1, uint8_t *tau2, const uint8_t *chaining_key, const uint8_t *data, size_t data_len) { + uint8_t tau0[WIREGUARD_HASH_LEN]; + uint8_t output[WIREGUARD_HASH_LEN + 1]; + + // tau0 = Hmac(key, input) + wireguard_hmac(tau0, chaining_key, WIREGUARD_HASH_LEN, data, data_len); + // tau1 := Hmac(tau0, 0x1) + output[0] = 1; + wireguard_hmac(output, tau0, WIREGUARD_HASH_LEN, output, 1); + memcpy(tau1, output, WIREGUARD_HASH_LEN); + + // tau2 := Hmac(tau0,tau1 || 0x2) + output[WIREGUARD_HASH_LEN] = 2; + wireguard_hmac(output, tau0, WIREGUARD_HASH_LEN, output, WIREGUARD_HASH_LEN + 1); + memcpy(tau2, output, WIREGUARD_HASH_LEN); + + // Wipe intermediates + crypto_zero(tau0, sizeof(tau0)); + crypto_zero(output, sizeof(output)); +} + +static void wireguard_kdf3(uint8_t *tau1, uint8_t *tau2, uint8_t *tau3, const uint8_t *chaining_key, const uint8_t *data, size_t data_len) { + uint8_t tau0[WIREGUARD_HASH_LEN]; + uint8_t output[WIREGUARD_HASH_LEN + 1]; + + // tau0 = Hmac(key, input) + wireguard_hmac(tau0, chaining_key, WIREGUARD_HASH_LEN, data, data_len); + // tau1 := Hmac(tau0, 0x1) + output[0] = 1; + wireguard_hmac(output, tau0, WIREGUARD_HASH_LEN, output, 1); + memcpy(tau1, output, WIREGUARD_HASH_LEN); + + // tau2 := Hmac(tau0,tau1 || 0x2) + output[WIREGUARD_HASH_LEN] = 2; + wireguard_hmac(output, tau0, WIREGUARD_HASH_LEN, output, WIREGUARD_HASH_LEN + 1); + memcpy(tau2, output, WIREGUARD_HASH_LEN); + + // tau3 := Hmac(tau0,tau1,tau2 || 0x3) + output[WIREGUARD_HASH_LEN] = 3; + wireguard_hmac(output, tau0, WIREGUARD_HASH_LEN, output, WIREGUARD_HASH_LEN + 1); + memcpy(tau3, output, WIREGUARD_HASH_LEN); + + // Wipe intermediates + crypto_zero(tau0, sizeof(tau0)); + crypto_zero(output, sizeof(output)); +} + +bool wireguard_check_replay(struct wireguard_keypair *keypair, uint64_t seq) { + // Implementation of packet replay window - as per RFC2401 + // Adapted from code in Appendix C at https://tools.ietf.org/html/rfc2401 + uint32_t diff; + bool result = false; + size_t ReplayWindowSize = sizeof(keypair->replay_bitmap); // 32 bits + + if (seq != 0) { + if (seq > keypair->replay_counter) { + // new larger sequence number + diff = seq - keypair->replay_counter; + if (diff < ReplayWindowSize) { + // In window + keypair->replay_bitmap <<= diff; + // set bit for this packet + keypair->replay_bitmap |= 1; + } else { + // This packet has a "way larger" + keypair->replay_bitmap = 1; + } + keypair->replay_counter = seq; + // larger is good + result = true; + } else { + diff = keypair->replay_counter - seq; + if (diff < ReplayWindowSize) { + if (keypair->replay_bitmap & ((uint32_t)1 << diff)) { + // already seen + } else { + // mark as seen + keypair->replay_bitmap |= ((uint32_t)1 << diff); + // out of order but good + result = true; + } + } else { + // too old or wrapped + } + } + } else { + // first == 0 or wrapped + } + return result; +} + +struct wireguard_keypair *get_peer_keypair_for_idx(struct wireguard_peer *peer, uint32_t idx) { + if (peer->curr_keypair.valid && peer->curr_keypair.local_index == idx) { + return &peer->curr_keypair; + } else if (peer->next_keypair.valid && peer->next_keypair.local_index == idx) { + return &peer->next_keypair; + } else if (peer->prev_keypair.valid && peer->prev_keypair.local_index == idx) { + return &peer->prev_keypair; + } + return NULL; +} + +static uint32_t wireguard_generate_unique_index(struct wireguard_device *device) { + // We need a random 32-bit number but make sure it's not already been used in the context of this device + uint32_t result; + uint8_t buf[4]; + int x; + struct wireguard_peer *peer; + bool existing; + do { + do { + wireguard_random_bytes(buf, 4); + result = U8TO32_LITTLE(buf); + } while ((result == 0) || (result == 0xFFFFFFFF)); // Don't allow 0 or 0xFFFFFFFF as valid values + + existing = false; + for (x=0; x < WIREGUARD_MAX_PEERS; x++) { + peer = &device->peers[x]; + existing = (result == peer->curr_keypair.local_index) || + (result == peer->prev_keypair.local_index) || + (result == peer->next_keypair.local_index) || + (result == peer->handshake.local_index); + + } + } while (existing); + + return result; +} + +static void wireguard_clamp_private_key(uint8_t *key) { + key[0] &= 248; + key[31] = (key[31] & 127) | 64; +} + +static void wireguard_generate_private_key(uint8_t *key) { + wireguard_random_bytes(key, WIREGUARD_PRIVATE_KEY_LEN); + wireguard_clamp_private_key(key); +} + +static bool wireguard_generate_public_key(uint8_t *public_key, const uint8_t *private_key) { + static const uint8_t basepoint[WIREGUARD_PUBLIC_KEY_LEN] = { 9 }; + bool result = false; + if (memcmp(private_key, zero_key, WIREGUARD_PUBLIC_KEY_LEN) != 0) { + result = (wireguard_x25519(public_key, private_key, basepoint) == 0); + } + return result; +} + +bool wireguard_check_mac1(struct wireguard_device *device, const uint8_t *data, size_t len, const uint8_t *mac1) { + bool result = false; + uint8_t calculated[WIREGUARD_COOKIE_LEN]; + wireguard_mac(calculated, data, len, device->label_mac1_key, WIREGUARD_SESSION_KEY_LEN); + if (crypto_equal(calculated, mac1, WIREGUARD_COOKIE_LEN)) { + result = true; + } + return result; +} + +bool wireguard_check_mac2(struct wireguard_device *device, const uint8_t *data, size_t len, uint8_t *source_addr_port, size_t source_length, const uint8_t *mac2) { + bool result = false; + uint8_t cookie[WIREGUARD_COOKIE_LEN]; + uint8_t calculated[WIREGUARD_COOKIE_LEN]; + + generate_peer_cookie(device, cookie, source_addr_port, source_length); + + wireguard_mac(calculated, data, len, cookie, WIREGUARD_COOKIE_LEN); + if (crypto_equal(calculated, mac2, WIREGUARD_COOKIE_LEN)) { + result = true; + } + return result; +} + +void handshake_destroy(struct wireguard_handshake *handshake) { + crypto_zero(handshake->ephemeral_private, WIREGUARD_PUBLIC_KEY_LEN); + crypto_zero(handshake->remote_ephemeral, WIREGUARD_PUBLIC_KEY_LEN); + crypto_zero(handshake->hash, WIREGUARD_HASH_LEN); + crypto_zero(handshake->chaining_key, WIREGUARD_HASH_LEN); + handshake->remote_index = 0; + handshake->local_index = 0; + handshake->valid = false; +} + +void keypair_destroy(struct wireguard_keypair *keypair) { + crypto_zero(keypair, sizeof(struct wireguard_keypair)); + keypair->valid = false; +} + +void keypair_update(struct wireguard_peer *peer, struct wireguard_keypair *received_keypair) { + bool key_is_next = (received_keypair == &peer->next_keypair); + if (key_is_next) { + peer->prev_keypair = peer->curr_keypair; + peer->curr_keypair = peer->next_keypair; + keypair_destroy(&peer->next_keypair); + } +} + +static void add_new_keypair(struct wireguard_peer *peer, struct wireguard_keypair new_keypair) { + if (new_keypair.initiator) { + if (peer->next_keypair.valid) { + peer->prev_keypair = peer->next_keypair; + keypair_destroy(&peer->next_keypair); + } else { + peer->prev_keypair = peer->curr_keypair; + } + peer->curr_keypair = new_keypair; + } else { + peer->next_keypair = new_keypair; + keypair_destroy(&peer->prev_keypair); + } +} + +void wireguard_start_session(struct wireguard_peer *peer, bool initiator) { + struct wireguard_handshake *handshake = &peer->handshake; + struct wireguard_keypair new_keypair; + + crypto_zero(&new_keypair, sizeof(struct wireguard_keypair)); + new_keypair.initiator = initiator; + new_keypair.local_index = handshake->local_index; + new_keypair.remote_index = handshake->remote_index; + + new_keypair.keypair_millis = wireguard_sys_now(); + new_keypair.sending_valid = true; + new_keypair.receiving_valid = true; + + // 5.4.5 Transport Data Key Derivation + // (Tsendi = Trecvr, Trecvi = Tsendr) := Kdf2(Ci = Cr,E) + if (new_keypair.initiator) { + wireguard_kdf2(new_keypair.sending_key, new_keypair.receiving_key, handshake->chaining_key, NULL, 0); + } else { + wireguard_kdf2(new_keypair.receiving_key, new_keypair.sending_key, handshake->chaining_key, NULL, 0); + } + + new_keypair.replay_bitmap = 0; + new_keypair.replay_counter = 0; + + new_keypair.last_tx = 0; + new_keypair.last_rx = 0; // No packets received yet + + new_keypair.valid = true; + + // Eprivi = Epubi = Eprivr = Epubr = Ci = Cr := E + crypto_zero(handshake->ephemeral_private, WIREGUARD_PUBLIC_KEY_LEN); + crypto_zero(handshake->remote_ephemeral, WIREGUARD_PUBLIC_KEY_LEN); + crypto_zero(handshake->hash, WIREGUARD_HASH_LEN); + crypto_zero(handshake->chaining_key, WIREGUARD_HASH_LEN); + handshake->remote_index = 0; + handshake->local_index = 0; + handshake->valid = false; + + add_new_keypair(peer, new_keypair); +} + +uint8_t wireguard_get_message_type(const uint8_t *data, size_t len) { + uint8_t result = MESSAGE_INVALID; + if (len >= 4) { + if ((data[1] == 0) && (data[2] == 0) && (data[3] == 0)) { + switch (data[0]) { + case MESSAGE_HANDSHAKE_INITIATION: + if (len == sizeof(struct message_handshake_initiation)) { + result = MESSAGE_HANDSHAKE_INITIATION; + } + break; + case MESSAGE_HANDSHAKE_RESPONSE: + if (len == sizeof(struct message_handshake_response)) { + result = MESSAGE_HANDSHAKE_RESPONSE; + } + break; + case MESSAGE_COOKIE_REPLY: + if (len == sizeof(struct message_cookie_reply)) { + result = MESSAGE_COOKIE_REPLY; + } + break; + case MESSAGE_TRANSPORT_DATA: + if (len >= sizeof(struct message_transport_data) + WIREGUARD_AUTHTAG_LEN) { + result = MESSAGE_TRANSPORT_DATA; + } + break; + default: + break; + } + } + } + return result; +} + +struct wireguard_peer *wireguard_process_initiation_message(struct wireguard_device *device, struct message_handshake_initiation *msg) { + struct wireguard_peer *ret_peer = NULL; + struct wireguard_peer *peer = NULL; + struct wireguard_handshake *handshake; + uint8_t key[WIREGUARD_SESSION_KEY_LEN]; + uint8_t chaining_key[WIREGUARD_HASH_LEN]; + uint8_t hash[WIREGUARD_HASH_LEN]; + uint8_t s[WIREGUARD_PUBLIC_KEY_LEN]; + uint8_t e[WIREGUARD_PUBLIC_KEY_LEN]; + uint8_t t[WIREGUARD_TAI64N_LEN]; + uint8_t dh_calculation[WIREGUARD_PUBLIC_KEY_LEN]; + uint32_t now; + bool rate_limit; + bool replay; + + // We are the responder, other end is the initiator + + // Ci := Hash(Construction) (precalculated hash) + memcpy(chaining_key, construction_hash, WIREGUARD_HASH_LEN); + + // Hi := Hash(Ci || Identifier + memcpy(hash, identifier_hash, WIREGUARD_HASH_LEN); + + // Hi := Hash(Hi || Spubr) + wireguard_mix_hash(hash, device->public_key, WIREGUARD_PUBLIC_KEY_LEN); + + // Ci := Kdf1(Ci, Epubi) + wireguard_kdf1(chaining_key, chaining_key, msg->ephemeral, WIREGUARD_PUBLIC_KEY_LEN); + + // msg.ephemeral := Epubi + memcpy(e, msg->ephemeral, WIREGUARD_PUBLIC_KEY_LEN); + + // Hi := Hash(Hi || msg.ephemeral) + wireguard_mix_hash(hash, msg->ephemeral, WIREGUARD_PUBLIC_KEY_LEN); + + // Calculate DH(Eprivi,Spubr) + wireguard_x25519(dh_calculation, device->private_key, e); + if (!crypto_equal(dh_calculation, zero_key, WIREGUARD_PUBLIC_KEY_LEN)) { + + // (Ci,k) := Kdf2(Ci,DH(Eprivi,Spubr)) + wireguard_kdf2(chaining_key, key, chaining_key, dh_calculation, WIREGUARD_PUBLIC_KEY_LEN); + + // msg.static := AEAD(k, 0, Spubi, Hi) + if (wireguard_aead_decrypt(s, msg->enc_static, sizeof(msg->enc_static), hash, WIREGUARD_HASH_LEN, 0, key)) { + // Hi := Hash(Hi || msg.static) + wireguard_mix_hash(hash, msg->enc_static, sizeof(msg->enc_static)); + + peer = peer_lookup_by_pubkey(device, s); + if (peer) { + handshake = &peer->handshake; + + // (Ci,k) := Kdf2(Ci,DH(Sprivi,Spubr)) + wireguard_kdf2(chaining_key, key, chaining_key, peer->public_key_dh, WIREGUARD_PUBLIC_KEY_LEN); + + // msg.timestamp := AEAD(k, 0, Timestamp(), Hi) + if (wireguard_aead_decrypt(t, msg->enc_timestamp, sizeof(msg->enc_timestamp), hash, WIREGUARD_HASH_LEN, 0, key)) { + // Hi := Hash(Hi || msg.timestamp) + wireguard_mix_hash(hash, msg->enc_timestamp, sizeof(msg->enc_timestamp)); + + now = wireguard_sys_now(); + + // Check that timestamp is increasing and we haven't had too many initiations (should only get one per peer every 5 seconds max?) + replay = (memcmp(t, peer->greatest_timestamp, WIREGUARD_TAI64N_LEN) <= 0); // tai64n is big endian so we can use memcmp to compare + rate_limit = (peer->last_initiation_rx - now) < (1000 / MAX_INITIATIONS_PER_SECOND); + + if (!replay && !rate_limit) { + // Success! Copy everything to peer + peer->last_initiation_rx = now; + if (memcmp(t, peer->greatest_timestamp, WIREGUARD_TAI64N_LEN) > 0) { + memcpy(peer->greatest_timestamp, t, WIREGUARD_TAI64N_LEN); + // TODO: Need to notify if the higher layers want to persist latest timestamp/nonce somewhere + } + memcpy(handshake->remote_ephemeral, e, WIREGUARD_PUBLIC_KEY_LEN); + memcpy(handshake->hash, hash, WIREGUARD_HASH_LEN); + memcpy(handshake->chaining_key, chaining_key, WIREGUARD_HASH_LEN); + handshake->remote_index = msg->sender; + handshake->valid = true; + handshake->initiator = false; + ret_peer = peer; + + } else { + // Ignore + } + } else { + // Failed to decrypt + } + } else { + // peer not found + } + } else { + // Failed to decrypt + } + } else { + // Bad X25519 + } + + crypto_zero(key, sizeof(key)); + crypto_zero(hash, sizeof(hash)); + crypto_zero(chaining_key, sizeof(chaining_key)); + crypto_zero(dh_calculation, sizeof(dh_calculation)); + + return ret_peer; +} + +bool wireguard_process_handshake_response(struct wireguard_device *device, struct wireguard_peer *peer, struct message_handshake_response *src) { + struct wireguard_handshake *handshake = &peer->handshake; + + bool result = false; + uint8_t key[WIREGUARD_SESSION_KEY_LEN]; + uint8_t hash[WIREGUARD_HASH_LEN]; + uint8_t chaining_key[WIREGUARD_HASH_LEN]; + uint8_t e[WIREGUARD_PUBLIC_KEY_LEN]; + uint8_t ephemeral_private[WIREGUARD_PUBLIC_KEY_LEN]; + uint8_t static_private[WIREGUARD_PUBLIC_KEY_LEN]; + uint8_t preshared_key[WIREGUARD_SESSION_KEY_LEN]; + uint8_t dh_calculation[WIREGUARD_PUBLIC_KEY_LEN]; + uint8_t tau[WIREGUARD_PUBLIC_KEY_LEN]; + + if (handshake->valid && handshake->initiator) { + + memcpy(hash, handshake->hash, WIREGUARD_HASH_LEN); + memcpy(chaining_key, handshake->chaining_key, WIREGUARD_HASH_LEN); + memcpy(ephemeral_private, handshake->ephemeral_private, WIREGUARD_PUBLIC_KEY_LEN); + memcpy(preshared_key, peer->preshared_key, WIREGUARD_SESSION_KEY_LEN); + + // (Eprivr, Epubr) := DH-Generate() + // Not required + + // Cr := Kdf1(Cr,Epubr) + wireguard_kdf1(chaining_key, chaining_key, src->ephemeral, WIREGUARD_PUBLIC_KEY_LEN); + + // msg.ephemeral := Epubr + memcpy(e, src->ephemeral, WIREGUARD_PUBLIC_KEY_LEN); + + // Hr := Hash(Hr || msg.ephemeral) + wireguard_mix_hash(hash, src->ephemeral, WIREGUARD_PUBLIC_KEY_LEN); + + // Cr := Kdf1(Cr, DH(Eprivr, Epubi)) + // Calculate DH(Eprivr, Epubi) + wireguard_x25519(dh_calculation, ephemeral_private, e); + if (!crypto_equal(dh_calculation, zero_key, WIREGUARD_PUBLIC_KEY_LEN)) { + wireguard_kdf1(chaining_key, chaining_key, dh_calculation, WIREGUARD_PUBLIC_KEY_LEN); + + // Cr := Kdf1(Cr, DH(Eprivr, Spubi)) + // CalculateDH(Eprivr, Spubi) + wireguard_x25519(dh_calculation, device->private_key, e); + if (!crypto_equal(dh_calculation, zero_key, WIREGUARD_PUBLIC_KEY_LEN)) { + wireguard_kdf1(chaining_key, chaining_key, dh_calculation, WIREGUARD_PUBLIC_KEY_LEN); + + // (Cr, t, k) := Kdf3(Cr, Q) + wireguard_kdf3(chaining_key, tau, key, chaining_key, peer->preshared_key, WIREGUARD_SESSION_KEY_LEN); + + // Hr := Hash(Hr | t) + wireguard_mix_hash(hash, tau, WIREGUARD_HASH_LEN); + + // msg.empty := AEAD(k, 0, E, Hr) + if (wireguard_aead_decrypt(NULL, src->enc_empty, sizeof(src->enc_empty), hash, WIREGUARD_HASH_LEN, 0, key)) { + // Hr := Hash(Hr | msg.empty) + // Not required as discarded + + //Copy details to handshake + memcpy(handshake->remote_ephemeral, e, WIREGUARD_HASH_LEN); + memcpy(handshake->hash, hash, WIREGUARD_HASH_LEN); + memcpy(handshake->chaining_key, chaining_key, WIREGUARD_HASH_LEN); + handshake->remote_index = src->sender; + + result = true; + } else { + // Decrypt failed + } + + } else { + // X25519 fail + } + + } else { + // X25519 fail + } + + } + crypto_zero(key, sizeof(key)); + crypto_zero(hash, sizeof(hash)); + crypto_zero(chaining_key, sizeof(chaining_key)); + crypto_zero(ephemeral_private, sizeof(ephemeral_private)); + crypto_zero(static_private, sizeof(static_private)); + crypto_zero(preshared_key, sizeof(preshared_key)); + crypto_zero(tau, sizeof(tau)); + + return result; +} + +bool wireguard_process_cookie_message(struct wireguard_device *device, struct wireguard_peer *peer, struct message_cookie_reply *src) { + uint8_t cookie[WIREGUARD_COOKIE_LEN]; + bool result = false; + + if (peer->handshake_mac1_valid) { + + result = wireguard_xaead_decrypt(cookie, src->enc_cookie, sizeof(src->enc_cookie), peer->handshake_mac1, WIREGUARD_COOKIE_LEN, src->nonce, peer->label_cookie_key); + + if (result) { + // 5.4.7 Under Load: Cookie Reply Message + // Upon receiving this message, if it is valid, the only thing the recipient of this message should do is store the cookie along with the time at which it was received + memcpy(peer->cookie, cookie, WIREGUARD_COOKIE_LEN); + peer->cookie_millis = wireguard_sys_now(); + peer->handshake_mac1_valid = false; + } + } else { + // We didn't send any initiation packet so we shouldn't be getting a cookie reply! + } + return result; +} + +bool wireguard_create_handshake_initiation(struct wireguard_device *device, struct wireguard_peer *peer, struct message_handshake_initiation *dst) { + uint8_t timestamp[WIREGUARD_TAI64N_LEN]; + uint8_t key[WIREGUARD_SESSION_KEY_LEN]; + uint8_t dh_calculation[WIREGUARD_PUBLIC_KEY_LEN]; + bool result = false; + + struct wireguard_handshake *handshake = &peer->handshake; + + memset(dst, 0, sizeof(struct message_handshake_initiation)); + + // Ci := Hash(Construction) (precalculated hash) + memcpy(handshake->chaining_key, construction_hash, WIREGUARD_HASH_LEN); + + // Hi := Hash(Ci || Identifier) + memcpy(handshake->hash, identifier_hash, WIREGUARD_HASH_LEN); + + // Hi := Hash(Hi || Spubr) + wireguard_mix_hash(handshake->hash, peer->public_key, WIREGUARD_PUBLIC_KEY_LEN); + + // (Eprivi, Epubi) := DH-Generate() + wireguard_generate_private_key(handshake->ephemeral_private); + if (wireguard_generate_public_key(dst->ephemeral, handshake->ephemeral_private)) { + + // Ci := Kdf1(Ci, Epubi) + wireguard_kdf1(handshake->chaining_key, handshake->chaining_key, dst->ephemeral, WIREGUARD_PUBLIC_KEY_LEN); + + // msg.ephemeral := Epubi + // Done above - public keys is calculated into dst->ephemeral + + // Hi := Hash(Hi || msg.ephemeral) + wireguard_mix_hash(handshake->hash, dst->ephemeral, WIREGUARD_PUBLIC_KEY_LEN); + + // Calculate DH(Eprivi,Spubr) + wireguard_x25519(dh_calculation, handshake->ephemeral_private, peer->public_key); + if (!crypto_equal(dh_calculation, zero_key, WIREGUARD_PUBLIC_KEY_LEN)) { + + // (Ci,k) := Kdf2(Ci,DH(Eprivi,Spubr)) + wireguard_kdf2(handshake->chaining_key, key, handshake->chaining_key, dh_calculation, WIREGUARD_PUBLIC_KEY_LEN); + + // msg.static := AEAD(k,0,Spubi, Hi) + wireguard_aead_encrypt(dst->enc_static, device->public_key, WIREGUARD_PUBLIC_KEY_LEN, handshake->hash, WIREGUARD_HASH_LEN, 0, key); + + // Hi := Hash(Hi || msg.static) + wireguard_mix_hash(handshake->hash, dst->enc_static, sizeof(dst->enc_static)); + + // (Ci,k) := Kdf2(Ci,DH(Sprivi,Spubr)) + // note DH(Sprivi,Spubr) is precomputed per peer + wireguard_kdf2(handshake->chaining_key, key, handshake->chaining_key, peer->public_key_dh, WIREGUARD_PUBLIC_KEY_LEN); + + // msg.timestamp := AEAD(k, 0, Timestamp(), Hi) + wireguard_tai64n_now(timestamp); + wireguard_aead_encrypt(dst->enc_timestamp, timestamp, WIREGUARD_TAI64N_LEN, handshake->hash, WIREGUARD_HASH_LEN, 0, key); + + // Hi := Hash(Hi || msg.timestamp) + wireguard_mix_hash(handshake->hash, dst->enc_timestamp, sizeof(dst->enc_timestamp)); + + dst->type = MESSAGE_HANDSHAKE_INITIATION; + dst->sender = wireguard_generate_unique_index(device); + + handshake->valid = true; + handshake->initiator = true; + handshake->local_index = dst->sender; + + result = true; + } + } + + if (result) { + // 5.4.4 Cookie MACs + // msg.mac1 := Mac(Hash(Label-Mac1 || Spubm' ), msgA) + // The value Hash(Label-Mac1 || Spubm' ) above can be pre-computed + wireguard_mac(dst->mac1, dst, (sizeof(struct message_handshake_initiation)-(2*WIREGUARD_COOKIE_LEN)), peer->label_mac1_key, WIREGUARD_SESSION_KEY_LEN); + + // if Lm = E or Lm ≥ 120: + if ((peer->cookie_millis == 0) || wireguard_expired(peer->cookie_millis, COOKIE_SECRET_MAX_AGE)) { + // msg.mac2 := 0 + crypto_zero(dst->mac2, WIREGUARD_COOKIE_LEN); + } else { + // msg.mac2 := Mac(Lm, msgB) + wireguard_mac(dst->mac2, dst, (sizeof(struct message_handshake_initiation)-(WIREGUARD_COOKIE_LEN)), peer->cookie, WIREGUARD_COOKIE_LEN); + + } + } + + crypto_zero(key, sizeof(key)); + crypto_zero(dh_calculation, sizeof(dh_calculation)); + return result; +} + +bool wireguard_create_handshake_response(struct wireguard_device *device, struct wireguard_peer *peer, struct message_handshake_response *dst) { + struct wireguard_handshake *handshake = &peer->handshake; + uint8_t key[WIREGUARD_SESSION_KEY_LEN]; + uint8_t dh_calculation[WIREGUARD_PUBLIC_KEY_LEN]; + uint8_t tau[WIREGUARD_HASH_LEN]; + bool result = false; + + memset(dst, 0, sizeof(struct message_handshake_response)); + + if (handshake->valid && !handshake->initiator) { + + // (Eprivr, Epubr) := DH-Generate() + wireguard_generate_private_key(handshake->ephemeral_private); + if (wireguard_generate_public_key(dst->ephemeral, handshake->ephemeral_private)) { + + // Cr := Kdf1(Cr,Epubr) + wireguard_kdf1(handshake->chaining_key, handshake->chaining_key, dst->ephemeral, WIREGUARD_PUBLIC_KEY_LEN); + + // msg.ephemeral := Epubr + // Copied above when generated + + // Hr := Hash(Hr || msg.ephemeral) + wireguard_mix_hash(handshake->hash, dst->ephemeral, WIREGUARD_PUBLIC_KEY_LEN); + + // Cr := Kdf1(Cr, DH(Eprivr, Epubi)) + // Calculate DH(Eprivi,Spubr) + wireguard_x25519(dh_calculation, handshake->ephemeral_private, handshake->remote_ephemeral); + if (!crypto_equal(dh_calculation, zero_key, WIREGUARD_PUBLIC_KEY_LEN)) { + wireguard_kdf1(handshake->chaining_key, handshake->chaining_key, dh_calculation, WIREGUARD_PUBLIC_KEY_LEN); + + // Cr := Kdf1(Cr, DH(Eprivr, Spubi)) + // Calculate DH(Eprivi,Spubr) + wireguard_x25519(dh_calculation, handshake->ephemeral_private, peer->public_key); + if (!crypto_equal(dh_calculation, zero_key, WIREGUARD_PUBLIC_KEY_LEN)) { + wireguard_kdf1(handshake->chaining_key, handshake->chaining_key, dh_calculation, WIREGUARD_PUBLIC_KEY_LEN); + + // (Cr, t, k) := Kdf3(Cr, Q) + wireguard_kdf3(handshake->chaining_key, tau, key, handshake->chaining_key, peer->preshared_key, WIREGUARD_SESSION_KEY_LEN); + + // Hr := Hash(Hr | t) + wireguard_mix_hash(handshake->hash, tau, WIREGUARD_HASH_LEN); + + // msg.empty := AEAD(k, 0, E, Hr) + wireguard_aead_encrypt(dst->enc_empty, NULL, 0, handshake->hash, WIREGUARD_HASH_LEN, 0, key); + + // Hr := Hash(Hr | msg.empty) + wireguard_mix_hash(handshake->hash, dst->enc_empty, sizeof(dst->enc_empty)); + + dst->type = MESSAGE_HANDSHAKE_RESPONSE; + dst->receiver = handshake->remote_index; + dst->sender = wireguard_generate_unique_index(device); + // Update handshake object too + handshake->local_index = dst->sender; + + result = true; + } else { + // Bad x25519 + } + } else { + // Bad x25519 + } + + } else { + // Failed to generate DH + } + } + + if (result) { + // 5.4.4 Cookie MACs + // msg.mac1 := Mac(Hash(Label-Mac1 || Spubm' ), msgA) + // The value Hash(Label-Mac1 || Spubm' ) above can be pre-computed + wireguard_mac(dst->mac1, dst, (sizeof(struct message_handshake_response)-(2*WIREGUARD_COOKIE_LEN)), peer->label_mac1_key, WIREGUARD_SESSION_KEY_LEN); + + // if Lm = E or Lm ≥ 120: + if ((peer->cookie_millis == 0) || wireguard_expired(peer->cookie_millis, COOKIE_SECRET_MAX_AGE)) { + // msg.mac2 := 0 + crypto_zero(dst->mac2, WIREGUARD_COOKIE_LEN); + } else { + // msg.mac2 := Mac(Lm, msgB) + wireguard_mac(dst->mac2, dst, (sizeof(struct message_handshake_response)-(WIREGUARD_COOKIE_LEN)), peer->cookie, WIREGUARD_COOKIE_LEN); + } + } + + crypto_zero(key, sizeof(key)); + crypto_zero(dh_calculation, sizeof(dh_calculation)); + crypto_zero(tau, sizeof(tau)); + return result; +} + +void wireguard_create_cookie_reply(struct wireguard_device *device, struct message_cookie_reply *dst, const uint8_t *mac1, uint32_t index, uint8_t *source_addr_port, size_t source_length) { + uint8_t cookie[WIREGUARD_COOKIE_LEN]; + crypto_zero(dst, sizeof(struct message_cookie_reply)); + dst->type = MESSAGE_COOKIE_REPLY; + dst->receiver = index; + wireguard_random_bytes(dst->nonce, COOKIE_NONCE_LEN); + generate_peer_cookie(device, cookie, source_addr_port, source_length); + wireguard_xaead_encrypt(dst->enc_cookie, cookie, WIREGUARD_COOKIE_LEN, mac1, WIREGUARD_COOKIE_LEN, dst->nonce, device->label_cookie_key); +} + +bool wireguard_peer_init(struct wireguard_device *device, struct wireguard_peer *peer, const uint8_t *public_key, const uint8_t *preshared_key) { + // Clear out structure + memset(peer, 0, sizeof(struct wireguard_peer)); + + if (device->valid) { + // Copy across the public key into our peer structure + memcpy(peer->public_key, public_key, WIREGUARD_PUBLIC_KEY_LEN); + if (preshared_key) { + memcpy(peer->preshared_key, preshared_key, WIREGUARD_SESSION_KEY_LEN); + } else { + crypto_zero(peer->preshared_key, WIREGUARD_SESSION_KEY_LEN); + } + + if (wireguard_x25519(peer->public_key_dh, device->private_key, peer->public_key) == 0) { + // Zero out handshake + memset(&peer->handshake, 0, sizeof(struct wireguard_handshake)); + peer->handshake.valid = false; + + // Zero out any cookie info - we haven't received one yet + peer->cookie_millis = 0; + memset(&peer->cookie, 0, WIREGUARD_COOKIE_LEN); + + // Precompute keys to deal with mac1/2 calculation + wireguard_mac_key(peer->label_mac1_key, peer->public_key, LABEL_MAC1, sizeof(LABEL_MAC1)); + wireguard_mac_key(peer->label_cookie_key, peer->public_key, LABEL_COOKIE, sizeof(LABEL_COOKIE)); + + peer->valid = true; + } else { + crypto_zero(peer->public_key_dh, WIREGUARD_PUBLIC_KEY_LEN); + } + } + return peer->valid; +} + +bool wireguard_device_init(struct wireguard_device *device, const uint8_t *private_key) { + // Set the private key and calculate public key from it + memcpy(device->private_key, private_key, WIREGUARD_PRIVATE_KEY_LEN); + // Ensure private key is correctly "clamped" + wireguard_clamp_private_key(device->private_key); + device->valid = wireguard_generate_public_key(device->public_key, private_key); + if (device->valid) { + generate_cookie_secret(device); + // 5.4.4 Cookie MACs - The value Hash(Label-Mac1 || Spubm' ) above can be pre-computed. + wireguard_mac_key(device->label_mac1_key, device->public_key, LABEL_MAC1, sizeof(LABEL_MAC1)); + // 5.4.7 Under Load: Cookie Reply Message - The value Hash(Label-Cookie || Spubm) above can be pre-computed. + wireguard_mac_key(device->label_cookie_key, device->public_key, LABEL_COOKIE, sizeof(LABEL_COOKIE)); + + } else { + crypto_zero(device->private_key, WIREGUARD_PRIVATE_KEY_LEN); + } + return device->valid; +} + +void wireguard_encrypt_packet(uint8_t *dst, const uint8_t *src, size_t src_len, struct wireguard_keypair *keypair) { + wireguard_aead_encrypt(dst, src, src_len, NULL, 0, keypair->sending_counter, keypair->sending_key); + keypair->sending_counter++; +} + +bool wireguard_decrypt_packet(uint8_t *dst, const uint8_t *src, size_t src_len, uint64_t counter, struct wireguard_keypair *keypair) { + return wireguard_aead_decrypt(dst, src, src_len, NULL, 0, counter, keypair->receiving_key); +} + +bool wireguard_base64_decode(const char *str, uint8_t *out, size_t *outlen) { + uint32_t accum = 0; // We accumulate upto four blocks of 6 bits into this to form 3 bytes output + uint8_t char_count = 0; // How many characters have we processed in this block + int byte_count = 3; // How many bytes are we expecting in current 4 char block + int len = 0; // result length in bytes + bool result = true; + uint8_t bits; + char c; + char *ptr; + int x; + size_t inlen; + + if (!str) { + return false; + } + + inlen = strlen(str); + + for (x = 0; x < inlen; x++) { + c = str[x]; + if (c == '=') { + // This is '=' padding at end of string - decrease the number of bytes to write + bits = 0; + byte_count--; + if (byte_count < 0) { + // Too much padding! + result = false; + break; + } + } else { + if (byte_count != 3) { + // Padding only allowed at end - this is a valid byte and we have already seen padding + result = false; + break; + } + ptr = strchr(base64_lookup, c); + if (ptr) { + bits = (uint8_t)((ptr - base64_lookup) & 0x3F); + } else { + // invalid character in input string + result = false; + break; + } + } + + accum = (accum << 6) | bits; + char_count++; + + if (char_count == 4) { + if (len + byte_count > *outlen) { + // Output buffer overflow + result = false; + break; + } + out[len++] = (uint8_t)((accum >> 16) & 0xFF); + if (byte_count > 1) { + out[len++] = (uint8_t)((accum >> 8) & 0xFF); + } + if (byte_count > 2) { + out[len++] = (uint8_t)(accum & 0xFF); + } + char_count = 0; + accum = 0; + } + } + if (char_count != 0) { + // We require padding to multiple of 3 input length - bytes are missing from output! + result = false; + } + *outlen = len; + return result; +} + +bool wireguard_base64_encode(const uint8_t *in, size_t inlen, char *out, size_t *outlen) { + bool result = false; + int read_offset = 0; + int write_offset = 0; + uint8_t byte1, byte2, byte3; + uint32_t tmp; + char c; + size_t len = 4 * ((inlen + 2) / 3); + int padding = (3 - (inlen % 3)); + if (padding > 2) padding = 0; + if (*outlen > len) { + + while (read_offset < inlen) { + // Read three bytes + byte1 = (read_offset < inlen) ? in[read_offset++] : 0; + byte2 = (read_offset < inlen) ? in[read_offset++] : 0; + byte3 = (read_offset < inlen) ? in[read_offset++] : 0; + // Turn into 24 bit intermediate + tmp = (byte1 << 16) | (byte2 << 8) | (byte3); + // Write out 4 characters each representing 6 bits of input + out[write_offset++] = base64_lookup[(tmp >> 18) & 0x3F]; + out[write_offset++] = base64_lookup[(tmp >> 12) & 0x3F]; + c = (write_offset < len - padding) ? base64_lookup[(tmp >> 6) & 0x3F] : '='; + out[write_offset++] = c; + c = (write_offset < len - padding) ? base64_lookup[(tmp) & 0x3F] : '='; + out[write_offset++] = c; + } + out[len] = '\0'; + *outlen = len; + result = true; + } else { + // Not enough data to put in base64 and null terminate + } + return result; +} diff --git a/lib/WireGuard-ESP32/src/wireguard.h b/lib/WireGuard-ESP32/src/wireguard.h new file mode 100644 index 000000000..961792a09 --- /dev/null +++ b/lib/WireGuard-ESP32/src/wireguard.h @@ -0,0 +1,287 @@ +/* + * Ported to ESP32 Arduino by Kenta Ida (fuga@fugafuga.org) + * The original license is below: + * 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. 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 + */ + +#ifndef _WIREGUARD_H_ +#define _WIREGUARD_H_ + +#include +#include +#include + +// Note: these are only required for definitions in device/peer for netif, udp_pcb, ip_addr_t and u16_t +#include "lwip/netif.h" +#include "lwip/udp.h" +#include "lwip/ip_addr.h" +#include "lwip/arch.h" + +// Platform-specific functions that need to be implemented per-platform +#include "wireguard-platform.h" + +// tai64n contains 64-bit seconds and 32-bit nano offset (12 bytes) +#define WIREGUARD_TAI64N_LEN (12) +// Auth algorithm is chacha20pol1305 which is 128bit (16 byte) authenticator +#define WIREGUARD_AUTHTAG_LEN (16) +// Hash algorithm is blake2s which makes 32 byte hashes +#define WIREGUARD_HASH_LEN (32) +// Public key algo is curve22519 which uses 32 byte keys +#define WIREGUARD_PUBLIC_KEY_LEN (32) +// Public key algo is curve22519 which uses 32 byte keys +#define WIREGUARD_PRIVATE_KEY_LEN (32) +// Symmetric session keys are chacha20/poly1305 which uses 32 byte keys +#define WIREGUARD_SESSION_KEY_LEN (32) + +// Timers / Limits +#define WIREGUARD_COOKIE_LEN (16) +#define COOKIE_SECRET_MAX_AGE (2 * 60) +#define COOKIE_NONCE_LEN (24) + +#define REKEY_AFTER_MESSAGES (1ULL << 60) +#define REJECT_AFTER_MESSAGES (0xFFFFFFFFFFFFFFFFULL - (1ULL << 13)) +#define REKEY_AFTER_TIME (120) +#define REJECT_AFTER_TIME (180) +#define REKEY_TIMEOUT (5) +#define KEEPALIVE_TIMEOUT (10) + +struct wireguard_keypair { + bool valid; + bool initiator; // Did we initiate this session (send the initiation packet rather than sending the response packet) + uint32_t keypair_millis; + + uint8_t sending_key[WIREGUARD_SESSION_KEY_LEN]; + bool sending_valid; + uint64_t sending_counter; + + uint8_t receiving_key[WIREGUARD_SESSION_KEY_LEN]; + bool receiving_valid; + + uint32_t last_tx; + uint32_t last_rx; + + uint32_t replay_bitmap; + uint64_t replay_counter; + + uint32_t local_index; // This is the index we generated for our end + uint32_t remote_index; // This is the index on the other end +}; + +struct wireguard_handshake { + bool valid; + bool initiator; + uint32_t local_index; + uint32_t remote_index; + uint8_t ephemeral_private[WIREGUARD_PRIVATE_KEY_LEN]; + uint8_t remote_ephemeral[WIREGUARD_PUBLIC_KEY_LEN]; + uint8_t hash[WIREGUARD_HASH_LEN]; + uint8_t chaining_key[WIREGUARD_HASH_LEN]; +}; + +struct wireguard_allowed_ip { + bool valid; + ip_addr_t ip; + ip_addr_t mask; +}; + +struct wireguard_peer { + bool valid; // Is this peer initialised? + bool active; // Should we be actively trying to connect? + + // This is the configured IP of the peer (endpoint) + ip_addr_t connect_ip; + u16_t connect_port; + // This is the latest received IP/port + ip_addr_t ip; + u16_t port; + // keep-alive interval in seconds, 0 is disable + uint16_t keepalive_interval; + + struct wireguard_allowed_ip allowed_source_ips[WIREGUARD_MAX_SRC_IPS]; + + uint8_t public_key[WIREGUARD_PUBLIC_KEY_LEN]; + uint8_t preshared_key[WIREGUARD_SESSION_KEY_LEN]; + + // Precomputed DH(Sprivi,Spubr) with device private key, and peer public key + uint8_t public_key_dh[WIREGUARD_PUBLIC_KEY_LEN]; + + // Session keypairs + struct wireguard_keypair curr_keypair; + struct wireguard_keypair prev_keypair; + struct wireguard_keypair next_keypair; + + // 5.1 Silence is a Virtue: The responder keeps track of the greatest timestamp received per peer + uint8_t greatest_timestamp[WIREGUARD_TAI64N_LEN]; + + // The active handshake that is happening + struct wireguard_handshake handshake; + + // Decrypted cookie from the responder + uint32_t cookie_millis; + uint8_t cookie[WIREGUARD_COOKIE_LEN]; + + // The latest mac1 we sent with initiation + bool handshake_mac1_valid; + uint8_t handshake_mac1[WIREGUARD_COOKIE_LEN]; + + // Precomputed keys for use in mac validation + uint8_t label_cookie_key[WIREGUARD_SESSION_KEY_LEN]; + uint8_t label_mac1_key[WIREGUARD_SESSION_KEY_LEN]; + + // The last time we received a valid initiation message + uint32_t last_initiation_rx; + // The last time we sent an initiation message to this peer + uint32_t last_initiation_tx; + + // last_tx and last_rx of data packets + uint32_t last_tx; + uint32_t last_rx; + + // We set this flag on RX/TX of packets if we think that we should initiate a new handshake + bool send_handshake; +}; + +struct wireguard_device { + // Maybe have a "Device private" member to abstract these? + struct netif *netif; + struct udp_pcb *udp_pcb; + + struct netif *underlying_netif; + + uint8_t public_key[WIREGUARD_PUBLIC_KEY_LEN]; + uint8_t private_key[WIREGUARD_PRIVATE_KEY_LEN]; + + uint8_t cookie_secret[WIREGUARD_HASH_LEN]; + uint32_t cookie_secret_millis; + + // Precalculated + uint8_t label_cookie_key[WIREGUARD_SESSION_KEY_LEN]; + uint8_t label_mac1_key[WIREGUARD_SESSION_KEY_LEN]; + + // List of peers associated with this device + struct wireguard_peer peers[WIREGUARD_MAX_PEERS]; + + bool valid; +}; + +#define MESSAGE_INVALID 0 +#define MESSAGE_HANDSHAKE_INITIATION 1 +#define MESSAGE_HANDSHAKE_RESPONSE 2 +#define MESSAGE_COOKIE_REPLY 3 +#define MESSAGE_TRANSPORT_DATA 4 + + +// 5.4.2 First Message: Initiator to Responder +struct message_handshake_initiation { + uint8_t type; + uint8_t reserved[3]; + uint32_t sender; + uint8_t ephemeral[32]; + uint8_t enc_static[32 + WIREGUARD_AUTHTAG_LEN]; + uint8_t enc_timestamp[WIREGUARD_TAI64N_LEN + WIREGUARD_AUTHTAG_LEN]; + uint8_t mac1[WIREGUARD_COOKIE_LEN]; + uint8_t mac2[WIREGUARD_COOKIE_LEN]; +} __attribute__ ((__packed__)); + +// 5.4.3 Second Message: Responder to Initiator +struct message_handshake_response { + uint8_t type; + uint8_t reserved[3]; + uint32_t sender; + uint32_t receiver; + uint8_t ephemeral[32]; + uint8_t enc_empty[0 + WIREGUARD_AUTHTAG_LEN]; + uint8_t mac1[WIREGUARD_COOKIE_LEN]; + uint8_t mac2[WIREGUARD_COOKIE_LEN]; +} __attribute__ ((__packed__)); + +// 5.4.7 Under Load: Cookie Reply Message +struct message_cookie_reply { + uint8_t type; + uint8_t reserved[3]; + uint32_t receiver; + uint8_t nonce[COOKIE_NONCE_LEN]; + uint8_t enc_cookie[WIREGUARD_COOKIE_LEN + WIREGUARD_AUTHTAG_LEN]; +} __attribute__ ((__packed__)); + +// 5.4.6 Subsequent Messages: Transport Data Messages +struct message_transport_data { + uint8_t type; + uint8_t reserved[3]; + uint32_t receiver; + uint8_t counter[8]; + // Followed by encrypted data + uint8_t enc_packet[]; +} __attribute__ ((__packed__)); + +// Initialise the WireGuard system - need to call this before anything else +void wireguard_init(); +bool wireguard_device_init(struct wireguard_device *device, const uint8_t *private_key); +bool wireguard_peer_init(struct wireguard_device *device, struct wireguard_peer *peer, const uint8_t *public_key, const uint8_t *preshared_key); + +struct wireguard_peer *peer_alloc(struct wireguard_device *device); +uint8_t wireguard_peer_index(struct wireguard_device *device, struct wireguard_peer *peer); +struct wireguard_peer *peer_lookup_by_pubkey(struct wireguard_device *device, uint8_t *public_key); +struct wireguard_peer *peer_lookup_by_peer_index(struct wireguard_device *device, uint8_t peer_index); +struct wireguard_peer *peer_lookup_by_receiver(struct wireguard_device *device, uint32_t receiver); +struct wireguard_peer *peer_lookup_by_handshake(struct wireguard_device *device, uint32_t receiver); + +void wireguard_start_session(struct wireguard_peer *peer, bool initiator); + +void keypair_update(struct wireguard_peer *peer, struct wireguard_keypair *received_keypair); +void keypair_destroy(struct wireguard_keypair *keypair); + +struct wireguard_keypair *get_peer_keypair_for_idx(struct wireguard_peer *peer, uint32_t idx); +bool wireguard_check_replay(struct wireguard_keypair *keypair, uint64_t seq); + +uint8_t wireguard_get_message_type(const uint8_t *data, size_t len); + +struct wireguard_peer *wireguard_process_initiation_message(struct wireguard_device *device, struct message_handshake_initiation *msg); +bool wireguard_process_handshake_response(struct wireguard_device *device, struct wireguard_peer *peer, struct message_handshake_response *src); +bool wireguard_process_cookie_message(struct wireguard_device *device, struct wireguard_peer *peer, struct message_cookie_reply *src); + +bool wireguard_create_handshake_initiation(struct wireguard_device *device, struct wireguard_peer *peer, struct message_handshake_initiation *dst); +bool wireguard_create_handshake_response(struct wireguard_device *device, struct wireguard_peer *peer, struct message_handshake_response *dst); +void wireguard_create_cookie_reply(struct wireguard_device *device, struct message_cookie_reply *dst, const uint8_t *mac1, uint32_t index, uint8_t *source_addr_port, size_t source_length); + + +bool wireguard_check_mac1(struct wireguard_device *device, const uint8_t *data, size_t len, const uint8_t *mac1); +bool wireguard_check_mac2(struct wireguard_device *device, const uint8_t *data, size_t len, uint8_t *source_addr_port, size_t source_length, const uint8_t *mac2); + +bool wireguard_expired(uint32_t created_millis, uint32_t valid_seconds); + +void wireguard_encrypt_packet(uint8_t *dst, const uint8_t *src, size_t src_len, struct wireguard_keypair *keypair); +bool wireguard_decrypt_packet(uint8_t *dst, const uint8_t *src, size_t src_len, uint64_t counter, struct wireguard_keypair *keypair); + +bool wireguard_base64_decode(const char *str, uint8_t *out, size_t *outlen); +bool wireguard_base64_encode(const uint8_t *in, size_t inlen, char *out, size_t *outlen); + +#endif /* _WIREGUARD_H_ */ diff --git a/lib/WireGuard-ESP32/src/wireguardif.c b/lib/WireGuard-ESP32/src/wireguardif.c new file mode 100644 index 000000000..d64ad8548 --- /dev/null +++ b/lib/WireGuard-ESP32/src/wireguardif.c @@ -0,0 +1,1028 @@ +/* + * Ported to ESP32 Arduino by Kenta Ida (fuga@fugafuga.org) + * The original license is below: + * + * 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. 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 + */ + +#include "wireguardif.h" + +#include +#include + +#include "lwip/netif.h" +#include "lwip/ip.h" +#include "lwip/udp.h" +#include "lwip/mem.h" +#include "lwip/sys.h" +#include "lwip/timeouts.h" + +#include "wireguard.h" +#include "crypto.h" +#include "esp_log.h" +#include "tcpip_adapter.h" + +#include "esp32-hal-log.h" + +#define WIREGUARDIF_TIMER_MSECS 400 + +#define TAG "[WireGuard] " + +static void update_peer_addr(struct wireguard_peer *peer, const ip_addr_t *addr, u16_t port) { + peer->ip = *addr; + peer->port = port; +} + +static struct wireguard_peer *peer_lookup_by_allowed_ip(struct wireguard_device *device, const ip_addr_t *ipaddr) { + struct wireguard_peer *result = NULL; + struct wireguard_peer *tmp; + int x; + int y; + for (x=0; (!result) && (x < WIREGUARD_MAX_PEERS); x++) { + tmp = &device->peers[x]; + if (tmp->valid) { + for (y=0; y < WIREGUARD_MAX_SRC_IPS; y++) { + if ((tmp->allowed_source_ips[y].valid) && ip_addr_netcmp(ipaddr, &tmp->allowed_source_ips[y].ip, ip_2_ip4(&tmp->allowed_source_ips[y].mask))) { + result = tmp; + break; + } + } + } + } + return result; +} + +static bool wireguardif_can_send_initiation(struct wireguard_peer *peer) { + return ((peer->last_initiation_tx == 0) || (wireguard_expired(peer->last_initiation_tx, REKEY_TIMEOUT))); +} + +static err_t wireguardif_peer_output(struct netif *netif, struct pbuf *q, struct wireguard_peer *peer) { + struct wireguard_device *device = (struct wireguard_device *)netif->state; + // Send to last know port, not the connect port + //TODO: Support DSCP and ECN - lwip requires this set on PCB globally, not per packet + return udp_sendto_if(device->udp_pcb, q, &peer->ip, peer->port, device->underlying_netif); +} + +static err_t wireguardif_device_output(struct wireguard_device *device, struct pbuf *q, const ip_addr_t *ipaddr, u16_t port) { + return udp_sendto_if(device->udp_pcb, q, ipaddr, port, device->underlying_netif); +} + +static err_t wireguardif_output_to_peer(struct netif *netif, struct pbuf *q, const ip_addr_t *ipaddr, struct wireguard_peer *peer) { + // The LWIP IP layer wants to send an IP packet out over the interface - we need to encrypt and send it to the peer + struct message_transport_data *hdr; + struct pbuf *pbuf; + err_t result; + size_t unpadded_len; + size_t padded_len; + size_t header_len = 16; + uint8_t *dst; + uint32_t now; + struct wireguard_keypair *keypair = &peer->curr_keypair; + + // Note: We may not be able to use the current keypair if we haven't received data, may need to resort to using previous keypair + if (keypair->valid && (!keypair->initiator) && (keypair->last_rx == 0)) { + keypair = &peer->prev_keypair; + } + + if (keypair->valid && (keypair->initiator || keypair->last_rx != 0)) { + + if ( + !wireguard_expired(keypair->keypair_millis, REJECT_AFTER_TIME) && + (keypair->sending_counter < REJECT_AFTER_MESSAGES) + ) { + + // Calculate the outgoing packet size - round up to next 16 bytes, add 16 bytes for header + if (q) { + // This is actual transport data + unpadded_len = q->tot_len; + } else { + // This is a keep-alive + unpadded_len = 0; + } + padded_len = (unpadded_len + 15) & 0xFFFFFFF0; // Round up to next 16 byte boundary + + // The buffer needs to be allocated from "transport" pool to leave room for LwIP generated IP headers + // The IP packet consists of 16 byte header (struct message_transport_data), data padded upto 16 byte boundary + encrypted auth tag (16 bytes) + pbuf = pbuf_alloc(PBUF_TRANSPORT, header_len + padded_len + WIREGUARD_AUTHTAG_LEN, PBUF_RAM); + if (pbuf) { + log_v(TAG "preparing transport data..."); + // Note: allocating pbuf from RAM above guarantees that the pbuf is in one section and not chained + // - i.e payload points to the contiguous memory region + memset(pbuf->payload, 0, pbuf->tot_len); + + hdr = (struct message_transport_data *)pbuf->payload; + + hdr->type = MESSAGE_TRANSPORT_DATA; + hdr->receiver = keypair->remote_index; + // Alignment required... pbuf_alloc has probably aligned data, but want to be sure + U64TO8_LITTLE(hdr->counter, keypair->sending_counter); + + // Copy the encrypted (padded) data to the output packet - chacha20poly1305_encrypt() can encrypt data in-place which avoids call to mem_malloc + dst = &hdr->enc_packet[0]; + if ((padded_len > 0) && q) { + // Note: before copying make sure we have inserted the IP header checksum + // The IP header checksum (and other checksums in the IP packet - e.g. ICMP) need to be calculated by LWIP before calling + // The Wireguard interface always needs checksums to be generated in software but the base netif may have some checksums generated by hardware + + // Copy pbuf to memory - handles case where pbuf is chained + pbuf_copy_partial(q, dst, unpadded_len, 0); + } + + // Then encrypt + wireguard_encrypt_packet(dst, dst, padded_len, keypair); + + result = wireguardif_peer_output(netif, pbuf, peer); + + if (result == ERR_OK) { + now = wireguard_sys_now(); + peer->last_tx = now; + keypair->last_tx = now; + } + + pbuf_free(pbuf); + + // Check to see if we should rekey + if (keypair->sending_counter >= REKEY_AFTER_MESSAGES) { + peer->send_handshake = true; + } else if (keypair->initiator && wireguard_expired(keypair->keypair_millis, REKEY_AFTER_TIME)) { + peer->send_handshake = true; + } + + } else { + // Failed to allocate memory + result = ERR_MEM; + } + } else { + // key has expired... + keypair_destroy(keypair); + result = ERR_CONN; + } + } else { + // No valid keys! + result = ERR_CONN; + } + return result; +} + +// This is used as the output function for the Wireguard netif +// The ipaddr here is the one inside the VPN which we use to lookup the correct peer/endpoint +static err_t wireguardif_output(struct netif *netif, struct pbuf *q, const ip4_addr_t *ip4addr) { + struct wireguard_device *device = (struct wireguard_device *)netif->state; + // Send to peer that matches dest IP + ip_addr_t ipaddr; + ip_addr_copy_from_ip4(ipaddr, *ip4addr); + struct wireguard_peer *peer = peer_lookup_by_allowed_ip(device, &ipaddr); + if (peer) { + return wireguardif_output_to_peer(netif, q, &ipaddr, peer); + } else { + return ERR_RTE; + } +} + +static void wireguardif_send_keepalive(struct wireguard_device *device, struct wireguard_peer *peer) { + // Send a NULL packet as a keep-alive + wireguardif_output_to_peer(device->netif, NULL, NULL, peer); +} + +static void wireguardif_process_response_message(struct wireguard_device *device, struct wireguard_peer *peer, struct message_handshake_response *response, const ip_addr_t *addr, u16_t port) { + if (wireguard_process_handshake_response(device, peer, response)) { + // Packet is good + // Update the peer location + log_i(TAG "good handshake from %08x:%d", addr->u_addr.ip4.addr, port); + update_peer_addr(peer, addr, port); + + wireguard_start_session(peer, true); + wireguardif_send_keepalive(device, peer); + + // Set the IF-UP flag on netif + netif_set_link_up(device->netif); + } else { + // Packet bad + log_i(TAG "bad handshake from %08x:%d", addr->u_addr.ip4.addr, port); + } +} + +static bool peer_add_ip(struct wireguard_peer *peer, ip_addr_t ip, ip_addr_t mask) { + bool result = false; + struct wireguard_allowed_ip *allowed; + int x; + // Look for existing match first + for (x=0; x < WIREGUARD_MAX_SRC_IPS; x++) { + allowed = &peer->allowed_source_ips[x]; + if ((allowed->valid) && ip_addr_cmp(&allowed->ip, &ip) && ip_addr_cmp(&allowed->mask, &mask)) { + result = true; + break; + } + } + if (!result) { + // Look for a free slot + for (x=0; x < WIREGUARD_MAX_SRC_IPS; x++) { + allowed = &peer->allowed_source_ips[x]; + if (!allowed->valid) { + allowed->valid = true; + allowed->ip = ip; + allowed->mask = mask; + result = true; + break; + } + } + } + return result; +} + +static void wireguardif_process_data_message(struct wireguard_device *device, struct wireguard_peer *peer, struct message_transport_data *data_hdr, size_t data_len, const ip_addr_t *addr, u16_t port) { + struct wireguard_keypair *keypair; + uint64_t nonce; + uint8_t *src; + size_t src_len; + struct pbuf *pbuf; + struct ip_hdr *iphdr; + ip_addr_t dest; + bool dest_ok = false; + int x; + uint32_t now; + uint16_t header_len = 0xFFFF; + uint32_t idx = data_hdr->receiver; + + keypair = get_peer_keypair_for_idx(peer, idx); + + if (keypair) { + if ( + (keypair->receiving_valid) && + !wireguard_expired(keypair->keypair_millis, REJECT_AFTER_TIME) && + (keypair->sending_counter < REJECT_AFTER_MESSAGES) + + ) { + + nonce = U8TO64_LITTLE(data_hdr->counter); + src = &data_hdr->enc_packet[0]; + src_len = data_len; + + // We don't know the unpadded size until we have decrypted the packet and validated/inspected the IP header + pbuf = pbuf_alloc(PBUF_TRANSPORT, src_len - WIREGUARD_AUTHTAG_LEN, PBUF_RAM); + if (pbuf) { + // Decrypt the packet + memset(pbuf->payload, 0, pbuf->tot_len); + if (wireguard_decrypt_packet(pbuf->payload, src, src_len, nonce, keypair)) { + + // 3. Since the packet has authenticated correctly, the source IP of the outer UDP/IP packet is used to update the endpoint for peer TrMv...WXX0. + // Update the peer location + update_peer_addr(peer, addr, port); + + now = wireguard_sys_now(); + keypair->last_rx = now; + peer->last_rx = now; + + // Might need to shuffle next key --> current keypair + keypair_update(peer, keypair); + + // Check to see if we should rekey + if (keypair->initiator && wireguard_expired(keypair->keypair_millis, REJECT_AFTER_TIME - peer->keepalive_interval - REKEY_TIMEOUT)) { + peer->send_handshake = true; + } + + // Make sure that link is reported as up + netif_set_link_up(device->netif); + + if (pbuf->tot_len > 0) { + //4a. Once the packet payload is decrypted, the interface has a plaintext packet. If this is not an IP packet, it is dropped. + iphdr = (struct ip_hdr *)pbuf->payload; + // Check for packet replay / dupes + if (wireguard_check_replay(keypair, nonce)) { + + // 4b. Otherwise, WireGuard checks to see if the source IP address of the plaintext inner-packet routes correspondingly in the cryptokey routing table + // Also check packet length! +#if LWIP_IPV4 + if (IPH_V(iphdr) == 4) { + ip_addr_copy_from_ip4(dest, iphdr->dest); + for (x=0; x < WIREGUARD_MAX_SRC_IPS; x++) { + if (peer->allowed_source_ips[x].valid) { + if (ip_addr_netcmp(&dest, &peer->allowed_source_ips[x].ip, ip_2_ip4(&peer->allowed_source_ips[x].mask))) { + dest_ok = true; + header_len = PP_NTOHS(IPH_LEN(iphdr)); + break; + } + } + } + } +#endif /* LWIP_IPV4 */ +#if LWIP_IPV6 + if (IPH_V(iphdr) == 6) { + // TODO: IPV6 support for route filtering + header_len = PP_NTOHS(IPH_LEN(iphdr)); + dest_ok = true; + } +#endif /* LWIP_IPV6 */ + if (header_len <= pbuf->tot_len) { + + // 5. If the plaintext packet has not been dropped, it is inserted into the receive queue of the wg0 interface. + if (dest_ok) { + // Send packet to be process by LWIP + ip_input(pbuf, device->netif); + // pbuf is owned by IP layer now + pbuf = NULL; + } + } else { + // IP header is corrupt or lied about packet size + } + } else { + // This is a duplicate packet / replayed / too far out of order + } + } else { + // This was a keep-alive packet + } + } + + if (pbuf) { + pbuf_free(pbuf); + } + } + + + } else { + //After Reject-After-Messages transport data messages or after the current secure session is Reject- After-Time seconds old, + // whichever comes first, WireGuard will refuse to send or receive any more transport data messages using the current secure session, + // until a new secure session is created through the 1-RTT handshake + keypair_destroy(keypair); + } + + } else { + // Could not locate valid keypair for remote index + } +} + +static struct pbuf *wireguardif_initiate_handshake(struct wireguard_device *device, struct wireguard_peer *peer, struct message_handshake_initiation *msg, err_t *error) { + struct pbuf *pbuf = NULL; + err_t err = ERR_OK; + if (wireguard_create_handshake_initiation(device, peer, msg)) { + // Send this packet out! + pbuf = pbuf_alloc(PBUF_TRANSPORT, sizeof(struct message_handshake_initiation), PBUF_RAM); + if (pbuf) { + err = pbuf_take(pbuf, msg, sizeof(struct message_handshake_initiation)); + if (err == ERR_OK) { + // OK! + } else { + pbuf_free(pbuf); + pbuf = NULL; + } + } else { + err = ERR_MEM; + } + } else { + err = ERR_ARG; + } + if (error) { + *error = err; + } + return pbuf; +} + +static void wireguardif_send_handshake_response(struct wireguard_device *device, struct wireguard_peer *peer) { + struct message_handshake_response packet; + struct pbuf *pbuf = NULL; + err_t err = ERR_OK; + + if (wireguard_create_handshake_response(device, peer, &packet)) { + + wireguard_start_session(peer, false); + + // Send this packet out! + pbuf = pbuf_alloc(PBUF_TRANSPORT, sizeof(struct message_handshake_response), PBUF_RAM); + if (pbuf) { + err = pbuf_take(pbuf, &packet, sizeof(struct message_handshake_response)); + if (err == ERR_OK) { + // OK! + wireguardif_peer_output(device->netif, pbuf, peer); + } + pbuf_free(pbuf); + } + } +} + +static size_t get_source_addr_port(const ip_addr_t *addr, u16_t port, uint8_t *buf, size_t buflen) { + size_t result = 0; + +#if LWIP_IPV4 + if (IP_IS_V4(addr) && (buflen >= 4)) { + U32TO8_BIG(buf + result, PP_NTOHL(ip4_addr_get_u32(ip_2_ip4(addr)))); + result += 4; + } +#endif +#if LWIP_IPV6 + if (IP_IS_V6(addr) && (buflen >= 16)) { + U16TO8_BIG(buf + result + 0, IP6_ADDR_BLOCK1(ip_2_ip6(addr))); + U16TO8_BIG(buf + result + 2, IP6_ADDR_BLOCK2(ip_2_ip6(addr))); + U16TO8_BIG(buf + result + 4, IP6_ADDR_BLOCK3(ip_2_ip6(addr))); + U16TO8_BIG(buf + result + 6, IP6_ADDR_BLOCK4(ip_2_ip6(addr))); + U16TO8_BIG(buf + result + 8, IP6_ADDR_BLOCK5(ip_2_ip6(addr))); + U16TO8_BIG(buf + result + 10, IP6_ADDR_BLOCK6(ip_2_ip6(addr))); + U16TO8_BIG(buf + result + 12, IP6_ADDR_BLOCK7(ip_2_ip6(addr))); + U16TO8_BIG(buf + result + 14, IP6_ADDR_BLOCK8(ip_2_ip6(addr))); + result += 16; + } +#endif + if (buflen >= result + 2) { + U16TO8_BIG(buf + result, port); + result += 2; + } + return result; +} + +static void wireguardif_send_handshake_cookie(struct wireguard_device *device, const uint8_t *mac1, uint32_t index, const ip_addr_t *addr, u16_t port) { + struct message_cookie_reply packet; + struct pbuf *pbuf = NULL; + err_t err = ERR_OK; + uint8_t source_buf[18]; + size_t source_len = get_source_addr_port(addr, port, source_buf, sizeof(source_buf)); + + wireguard_create_cookie_reply(device, &packet, mac1, index, source_buf, source_len); + + // Send this packet out! + pbuf = pbuf_alloc(PBUF_TRANSPORT, sizeof(struct message_cookie_reply), PBUF_RAM); + if (pbuf) { + err = pbuf_take(pbuf, &packet, sizeof(struct message_cookie_reply)); + if (err == ERR_OK) { + wireguardif_device_output(device, pbuf, addr, port); + } + pbuf_free(pbuf); + } +} + +static bool wireguardif_check_initiation_message(struct wireguard_device *device, struct message_handshake_initiation *msg, const ip_addr_t *addr, u16_t port) { + bool result = false; + uint8_t *data = (uint8_t *)msg; + uint8_t source_buf[18]; + size_t source_len; + // We received an initiation packet check it is valid + + if (wireguard_check_mac1(device, data, sizeof(struct message_handshake_initiation) - (2 * WIREGUARD_COOKIE_LEN), msg->mac1)) { + // mac1 is valid! + if (!wireguard_is_under_load()) { + // If we aren't under load we only need mac1 to be correct + result = true; + } else { + // If we are under load then check mac2 + source_len = get_source_addr_port(addr, port, source_buf, sizeof(source_buf)); + + result = wireguard_check_mac2(device, data, sizeof(struct message_handshake_initiation) - (WIREGUARD_COOKIE_LEN), source_buf, source_len, msg->mac2); + + if (!result) { + // mac2 is invalid (cookie may have expired) or not present + // 5.3 Denial of Service Mitigation & Cookies + // If the responder receives a message with a valid msg.mac1 yet with an invalid msg.mac2, and is under load, it may respond with a cookie reply message + wireguardif_send_handshake_cookie(device, msg->mac1, msg->sender, addr, port); + } + } + + } else { + // mac1 is invalid + } + return result; +} + +static bool wireguardif_check_response_message(struct wireguard_device *device, struct message_handshake_response *msg, const ip_addr_t *addr, u16_t port) { + bool result = false; + uint8_t *data = (uint8_t *)msg; + uint8_t source_buf[18]; + size_t source_len; + // We received an initiation packet check it is valid + + if (wireguard_check_mac1(device, data, sizeof(struct message_handshake_response) - (2 * WIREGUARD_COOKIE_LEN), msg->mac1)) { + // mac1 is valid! + if (!wireguard_is_under_load()) { + // If we aren't under load we only need mac1 to be correct + result = true; + } else { + // If we are under load then check mac2 + source_len = get_source_addr_port(addr, port, source_buf, sizeof(source_buf)); + + result = wireguard_check_mac2(device, data, sizeof(struct message_handshake_response) - (WIREGUARD_COOKIE_LEN), source_buf, source_len, msg->mac2); + + if (!result) { + // mac2 is invalid (cookie may have expired) or not present + // 5.3 Denial of Service Mitigation & Cookies + // If the responder receives a message with a valid msg.mac1 yet with an invalid msg.mac2, and is under load, it may respond with a cookie reply message + wireguardif_send_handshake_cookie(device, msg->mac1, msg->sender, addr, port); + } + } + + } else { + // mac1 is invalid + } + return result; +} + + +void wireguardif_network_rx(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port) { + LWIP_ASSERT("wireguardif_network_rx: invalid arg", arg != NULL); + LWIP_ASSERT("wireguardif_network_rx: invalid pbuf", p != NULL); + // We have received a packet from the base_netif to our UDP port - process this as a possible Wireguard packet + struct wireguard_device *device = (struct wireguard_device *)arg; + struct wireguard_peer *peer; + uint8_t *data = p->payload; + size_t len = p->len; // This buf, not chained ones + + struct message_handshake_initiation *msg_initiation; + struct message_handshake_response *msg_response; + struct message_cookie_reply *msg_cookie; + struct message_transport_data *msg_data; + + uint8_t type = wireguard_get_message_type(data, len); + ESP_LOGV(TAG, "network_rx: %08x:%d", addr->u_addr.ip4.addr, port); + + switch (type) { + case MESSAGE_HANDSHAKE_INITIATION: + msg_initiation = (struct message_handshake_initiation *)data; + log_i(TAG "HANDSHAKE_INITIATION: %08x:%d", addr->u_addr.ip4.addr, port); + // Check mac1 (and optionally mac2) are correct - note it may internally generate a cookie reply packet + if (wireguardif_check_initiation_message(device, msg_initiation, addr, port)) { + + peer = wireguard_process_initiation_message(device, msg_initiation); + if (peer) { + // Update the peer location + update_peer_addr(peer, addr, port); + + // Send back a handshake response + wireguardif_send_handshake_response(device, peer); + } + } + break; + + case MESSAGE_HANDSHAKE_RESPONSE: + log_i(TAG "HANDSHAKE_RESPONSE: %08x:%d", addr->u_addr.ip4.addr, port); + msg_response = (struct message_handshake_response *)data; + + // Check mac1 (and optionally mac2) are correct - note it may internally generate a cookie reply packet + if (wireguardif_check_response_message(device, msg_response, addr, port)) { + + peer = peer_lookup_by_handshake(device, msg_response->receiver); + if (peer) { + // Process the handshake response + wireguardif_process_response_message(device, peer, msg_response, addr, port); + } + } + break; + + case MESSAGE_COOKIE_REPLY: + log_i(TAG "COOKIE_REPLY: %08x:%d", addr->u_addr.ip4.addr, port); + msg_cookie = (struct message_cookie_reply *)data; + peer = peer_lookup_by_handshake(device, msg_cookie->receiver); + if (peer) { + if (wireguard_process_cookie_message(device, peer, msg_cookie)) { + // Update the peer location + update_peer_addr(peer, addr, port); + + // Don't send anything out - we stay quiet until the next initiation message + } + } + break; + + case MESSAGE_TRANSPORT_DATA: + ESP_LOGV(TAG, "TRANSPORT_DATA: %08x:%d", addr->u_addr.ip4.addr, port); + + msg_data = (struct message_transport_data *)data; + peer = peer_lookup_by_receiver(device, msg_data->receiver); + if (peer) { + // header is 16 bytes long so take that off the length + wireguardif_process_data_message(device, peer, msg_data, len - 16, addr, port); + } + break; + + default: + // Unknown or bad packet header + break; + } + // Release data! + pbuf_free(p); +} + +static err_t wireguard_start_handshake(struct netif *netif, struct wireguard_peer *peer) { + struct wireguard_device *device = (struct wireguard_device *)netif->state; + err_t result; + struct pbuf *pbuf; + struct message_handshake_initiation msg; + + pbuf = wireguardif_initiate_handshake(device, peer, &msg, &result); + if (pbuf) { + result = wireguardif_peer_output(netif, pbuf, peer); + log_i(TAG "start handshake %08x,%d - %d", peer->ip.u_addr.ip4.addr, peer->port, result); + pbuf_free(pbuf); + peer->send_handshake = false; + peer->last_initiation_tx = wireguard_sys_now(); + memcpy(peer->handshake_mac1, msg.mac1, WIREGUARD_COOKIE_LEN); + peer->handshake_mac1_valid = true; + } + return result; +} + +static err_t wireguardif_lookup_peer(struct netif *netif, u8_t peer_index, struct wireguard_peer **out) { + LWIP_ASSERT("netif != NULL", (netif != NULL)); + LWIP_ASSERT("state != NULL", (netif->state != NULL)); + struct wireguard_device *device = (struct wireguard_device *)netif->state; + struct wireguard_peer *peer = NULL; + err_t result; + + if (device->valid) { + peer = peer_lookup_by_peer_index(device, peer_index); + if (peer) { + result = ERR_OK; + } else { + result = ERR_ARG; + } + } else { + result = ERR_ARG; + } + *out = peer; + return result; +} + +err_t wireguardif_connect(struct netif *netif, u8_t peer_index) { + struct wireguard_peer *peer; + err_t result = wireguardif_lookup_peer(netif, peer_index, &peer); + if (result == ERR_OK) { + // Check that a valid connect ip and port have been set + if (!ip_addr_isany(&peer->connect_ip) && (peer->connect_port > 0)) { + // Set the flag that we want to try connecting + peer->active = true; + peer->ip = peer->connect_ip; + peer->port = peer->connect_port; + result = ERR_OK; + } else { + result = ERR_ARG; + } + } + return result; +} + +err_t wireguardif_disconnect(struct netif *netif, u8_t peer_index) { + struct wireguard_peer *peer; + err_t result = wireguardif_lookup_peer(netif, peer_index, &peer); + if (result == ERR_OK) { + // Set the flag that we want to try connecting + peer->active = false; + // Wipe out current keys + keypair_destroy(&peer->next_keypair); + keypair_destroy(&peer->curr_keypair); + keypair_destroy(&peer->prev_keypair); + result = ERR_OK; + } + return result; +} + +err_t wireguardif_peer_is_up(struct netif *netif, u8_t peer_index, ip_addr_t *current_ip, u16_t *current_port) { + struct wireguard_peer *peer; + err_t result = wireguardif_lookup_peer(netif, peer_index, &peer); + if (result == ERR_OK) { + if ((peer->curr_keypair.valid) || (peer->prev_keypair.valid)) { + result = ERR_OK; + } else { + result = ERR_CONN; + } + if (current_ip) { + *current_ip = peer->ip; + } + if (current_port) { + *current_port = peer->port; + } + } + return result; +} + +err_t wireguardif_remove_peer(struct netif *netif, u8_t peer_index) { + struct wireguard_peer *peer; + err_t result = wireguardif_lookup_peer(netif, peer_index, &peer); + if (result == ERR_OK) { + crypto_zero(peer, sizeof(struct wireguard_peer)); + peer->valid = false; + result = ERR_OK; + } + return result; +} + +err_t wireguardif_update_endpoint(struct netif *netif, u8_t peer_index, const ip_addr_t *ip, u16_t port) { + struct wireguard_peer *peer; + err_t result = wireguardif_lookup_peer(netif, peer_index, &peer); + if (result == ERR_OK) { + peer->connect_ip = *ip; + peer->connect_port = port; + result = ERR_OK; + } + return result; +} + + +err_t wireguardif_add_peer(struct netif *netif, struct wireguardif_peer *p, u8_t *peer_index) { + LWIP_ASSERT("netif != NULL", (netif != NULL)); + LWIP_ASSERT("state != NULL", (netif->state != NULL)); + LWIP_ASSERT("p != NULL", (p != NULL)); + struct wireguard_device *device = (struct wireguard_device *)netif->state; + err_t result; + uint8_t public_key[WIREGUARD_PUBLIC_KEY_LEN]; + size_t public_key_len = sizeof(public_key); + struct wireguard_peer *peer = NULL; + + uint32_t t1 = wireguard_sys_now(); + + if (wireguard_base64_decode(p->public_key, public_key, &public_key_len) + && (public_key_len == WIREGUARD_PUBLIC_KEY_LEN)) { + + // See if the peer is already registered + peer = peer_lookup_by_pubkey(device, public_key); + if (!peer) { + // Not active - see if we have room to allocate a new one + peer = peer_alloc(device); + if (peer) { + + if (wireguard_peer_init(device, peer, public_key, p->preshared_key)) { + + peer->connect_ip = p->endpoint_ip; + peer->connect_port = p->endport_port; + peer->ip = peer->connect_ip; + peer->port = peer->connect_port; + if (p->keep_alive == WIREGUARDIF_KEEPALIVE_DEFAULT) { + peer->keepalive_interval = KEEPALIVE_TIMEOUT; + } else { + peer->keepalive_interval = p->keep_alive; + } + peer_add_ip(peer, p->allowed_ip, p->allowed_mask); + memcpy(peer->greatest_timestamp, p->greatest_timestamp, sizeof(peer->greatest_timestamp)); + + result = ERR_OK; + } else { + result = ERR_ARG; + } + } else { + result = ERR_MEM; + } + } else { + result = ERR_OK; + } + } else { + result = ERR_ARG; + } + + uint32_t t2 = wireguard_sys_now(); + log_i(TAG "Adding peer took %ums\r\n", (t2-t1)); + + if (peer_index) { + if (peer) { + *peer_index = wireguard_peer_index(device, peer); + } else { + *peer_index = WIREGUARDIF_INVALID_INDEX; + } + } + return result; +} + +static bool should_send_initiation(struct wireguard_peer *peer) { + bool result = false; + if (wireguardif_can_send_initiation(peer)) { + if (peer->send_handshake) { + result = true; + } else if (peer->curr_keypair.valid && !peer->curr_keypair.initiator && wireguard_expired(peer->curr_keypair.keypair_millis, REJECT_AFTER_TIME - peer->keepalive_interval)) { + result = true; + } else if (!peer->curr_keypair.valid && peer->active) { + result = true; + } + } + return result; +} + +static bool should_send_keepalive(struct wireguard_peer *peer) { + bool result = false; + if (peer->keepalive_interval > 0) { + if ((peer->curr_keypair.valid) || (peer->prev_keypair.valid)) { + if (wireguard_expired(peer->last_tx, peer->keepalive_interval)) { + result = true; + } + } + } + return result; +} + +static bool should_destroy_current_keypair(struct wireguard_peer *peer) { + bool result = false; + if (peer->curr_keypair.valid && + (wireguard_expired(peer->curr_keypair.keypair_millis, REJECT_AFTER_TIME) || + (peer->curr_keypair.sending_counter >= REJECT_AFTER_MESSAGES)) + ) { + result = true; + } + return result; +} + +static bool should_reset_peer(struct wireguard_peer *peer) { + bool result = false; + if (peer->curr_keypair.valid && (wireguard_expired(peer->curr_keypair.keypair_millis, REJECT_AFTER_TIME * 3))) { + result = true; + } + return result; +} + +static void wireguardif_tmr(void *arg) { + struct wireguard_device *device = (struct wireguard_device *)arg; + struct wireguard_peer *peer; + int x; + // Reschedule this timer + sys_timeout(WIREGUARDIF_TIMER_MSECS, wireguardif_tmr, device); + + // Check periodic things + bool link_up = false; + for (x=0; x < WIREGUARD_MAX_PEERS; x++) { + peer = &device->peers[x]; + if (peer->valid) { + // Do we need to rekey / send a handshake? + if (should_reset_peer(peer)) { + // Nothing back for too long - we should wipe out all crypto state + keypair_destroy(&peer->next_keypair); + keypair_destroy(&peer->curr_keypair); + keypair_destroy(&peer->prev_keypair); + handshake_destroy(&peer->handshake); + + // Revert back to default IP/port if these were altered + peer->ip = peer->connect_ip; + peer->port = peer->connect_port; + } + if (should_destroy_current_keypair(peer)) { + // Destroy current keypair + keypair_destroy(&peer->curr_keypair); + } + if (should_send_keepalive(peer)) { + wireguardif_send_keepalive(device, peer); + } + if (should_send_initiation(peer)) { + wireguard_start_handshake(device->netif, peer); + } + + if ((peer->curr_keypair.valid) || (peer->prev_keypair.valid)) { + link_up = true; + } + } + } + + if (!link_up) { + // Clear the IF-UP flag on netif + netif_set_link_down(device->netif); + } +} + +void wireguardif_shutdown(struct netif *netif) { + LWIP_ASSERT("netif != NULL", (netif != NULL)); + LWIP_ASSERT("state != NULL", (netif->state != NULL)); + + struct wireguard_device * device = (struct wireguard_device *)netif->state; + // Disable timer. + sys_untimeout(wireguardif_tmr, device); + // remove UDP context. + if( device->udp_pcb ) { + udp_disconnect(device->udp_pcb); + udp_remove(device->udp_pcb); + device->udp_pcb = NULL; + } + // remove device context. + free(device); + netif->state = NULL; +} + +err_t wireguardif_init(struct netif *netif) { + err_t result; + struct wireguardif_init_data *init_data; + struct wireguard_device *device; + struct udp_pcb *udp; + uint8_t private_key[WIREGUARD_PRIVATE_KEY_LEN]; + size_t private_key_len = sizeof(private_key); + + struct netif* underlying_netif; + tcpip_adapter_get_netif(TCPIP_ADAPTER_IF_STA, &underlying_netif); + log_i(TAG "underlying_netif = %p", underlying_netif); + + LWIP_ASSERT("netif != NULL", (netif != NULL)); + LWIP_ASSERT("state != NULL", (netif->state != NULL)); + + // We need to initialise the wireguard module + wireguard_init(); + log_i(TAG "wireguard module initialized."); + + if (netif && netif->state) { + + // The init data is passed into the netif_add call as the 'state' - we will replace this with our private state data + init_data = (struct wireguardif_init_data *)netif->state; + + // Clear out and set if function is successful + netif->state = NULL; + + if (wireguard_base64_decode(init_data->private_key, private_key, &private_key_len) + && (private_key_len == WIREGUARD_PRIVATE_KEY_LEN)) { + + udp = udp_new(); + + if (udp) { + result = udp_bind(udp, IP_ADDR_ANY, init_data->listen_port); // Note this listens on all interfaces! Really just want the passed netif + if (result == ERR_OK) { + device = (struct wireguard_device *)mem_calloc(1, sizeof(struct wireguard_device)); + if (device) { + device->netif = netif; + device->underlying_netif = underlying_netif; + //udp_bind_netif(udp, underlying_netif); + + device->udp_pcb = udp; + log_d(TAG "start device initialization"); + // Per-wireguard netif/device setup + uint32_t t1 = wireguard_sys_now(); + if (wireguard_device_init(device, private_key)) { + uint32_t t2 = wireguard_sys_now(); + log_d(TAG "Device init took %ums\r\n", (t2-t1)); + +#if LWIP_CHECKSUM_CTRL_PER_NETIF + NETIF_SET_CHECKSUM_CTRL(netif, NETIF_CHECKSUM_ENABLE_ALL); +#endif + netif->state = device; + netif->name[0] = 'w'; + netif->name[1] = 'g'; + netif->output = wireguardif_output; + netif->linkoutput = NULL; + netif->hwaddr_len = 0; + netif->mtu = WIREGUARDIF_MTU; + // We set up no state flags here - caller should set them + // NETIF_FLAG_LINK_UP is automatically set/cleared when at least one peer is connected + netif->flags = 0; + + udp_recv(udp, wireguardif_network_rx, device); + + // Start a periodic timer for this wireguard device + sys_timeout(WIREGUARDIF_TIMER_MSECS, wireguardif_tmr, device); + + result = ERR_OK; + } else { + log_e(TAG "failed to initialize WireGuard device."); + mem_free(device); + device = NULL; + udp_remove(udp); + result = ERR_ARG; + } + } else { + log_e(TAG "failed to allocate device context."); + udp_remove(udp); + result = ERR_MEM; + } + } else { + log_e(TAG "failed to bind UDP err=%d", result); + udp_remove(udp); + } + + } else { + log_e(TAG "failed to allocate UDP"); + result = ERR_MEM; + } + } else { + log_e(TAG "invalid init_data private key"); + result = ERR_ARG; + } + } else { + log_e(TAG "netif or state is NULL: netif=%p, netif.state:%p", netif, netif ? netif->state : NULL); + result = ERR_ARG; + } + return result; +} + +void wireguardif_peer_init(struct wireguardif_peer *peer) { + LWIP_ASSERT("peer != NULL", (peer != NULL)); + memset(peer, 0, sizeof(struct wireguardif_peer)); + // Caller must provide 'public_key' + peer->public_key = NULL; + ip_addr_set_any(false, &peer->endpoint_ip); + peer->endport_port = WIREGUARDIF_DEFAULT_PORT; + peer->keep_alive = WIREGUARDIF_KEEPALIVE_DEFAULT; + ip_addr_set_any(false, &peer->allowed_ip); + ip_addr_set_any(false, &peer->allowed_mask); + memset(peer->greatest_timestamp, 0, sizeof(peer->greatest_timestamp)); + peer->preshared_key = NULL; +} diff --git a/lib/WireGuard-ESP32/src/wireguardif.h b/lib/WireGuard-ESP32/src/wireguardif.h new file mode 100644 index 000000000..ad9d4a15b --- /dev/null +++ b/lib/WireGuard-ESP32/src/wireguardif.h @@ -0,0 +1,137 @@ +/* + * Ported to ESP32 Arduino by Kenta Ida (fuga@fugafuga.org) + * The original license is below: + * + * 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. 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 + */ + + +#ifndef _WIREGUARDIF_H_ +#define _WIREGUARDIF_H_ + +#include "lwip/arch.h" +#include "lwip/netif.h" +#include "lwip/ip_addr.h" + +// Default MTU for WireGuard is 1420 bytes +#define WIREGUARDIF_MTU (1420) + +#define WIREGUARDIF_DEFAULT_PORT (51820) +#define WIREGUARDIF_KEEPALIVE_DEFAULT (0xFFFF) + +struct wireguardif_init_data { + // Required: the private key of this WireGuard network interface + const char *private_key; + // Required: What UDP port to listen on + u16_t listen_port; + // Optional: restrict send/receive of encapsulated WireGuard traffic to this network interface only (NULL to use routing table) + struct netif *bind_netif; +}; + +struct wireguardif_peer { + const char *public_key; + // Optional pre-shared key (32 bytes) - make sure this is NULL if not to be used + const uint8_t *preshared_key; + // tai64n of largest timestamp we have seen during handshake to avoid replays + uint8_t greatest_timestamp[12]; + + // Allowed ip/netmask (can add additional later but at least one is required) + ip_addr_t allowed_ip; + ip_addr_t allowed_mask; + + // End-point details (may be blank) + ip_addr_t endpoint_ip; + u16_t endport_port; + u16_t keep_alive; +}; + +#define WIREGUARDIF_INVALID_INDEX (0xFF) + +/* static struct netif wg_netif_struct = {0}; + * struct wireguard_interface wg; + * wg.private_key = "abcdefxxx..xxxxx="; + * wg.listen_port = 51820; + * wg.bind_netif = NULL; // Pass netif to listen on, NULL for all interfaces + * + * netif = netif_add(&netif_struct, &ipaddr, &netmask, &gateway, &wg, &wireguardif_init, &ip_input); + * + * netif_set_up(wg_net); + * + * struct wireguardif_peer peer; + * wireguardif_peer_init(&peer); + * peer.public_key = "apoehc...4322abcdfejg=; + * peer.preshared_key = NULL; + * peer.allowed_ip = allowed_ip; + * peer.allowed_mask = allowed_mask; + * + * // If you want to enable output connection + * peer.endpoint_ip = peer_ip; + * peer.endport_port = 12345; + * + * uint8_t wireguard_peer_index; + * wireguardif_add_peer(netif, &peer, &wireguard_peer_index); + * + * if ((wireguard_peer_index != WIREGUARDIF_INVALID_INDEX) && !ip_addr_isany(&peer.endpoint_ip)) { + * // Start outbound connection to peer + * wireguardif_connect(wg_net, wireguard_peer_index); + * } + * + */ + +// Initialise a new WireGuard network interface (netif) +err_t wireguardif_init(struct netif *netif); + +// Shutdown a WireGuard network interface (netif) +void wireguardif_shutdown(struct netif *netif); + +// Helper to initialise the peer struct with defaults +void wireguardif_peer_init(struct wireguardif_peer *peer); + +// Add a new peer to the specified interface - see wireguard.h for maximum number of peers allowed +// On success the peer_index can be used to reference this peer in future function calls +err_t wireguardif_add_peer(struct netif *netif, struct wireguardif_peer *peer, u8_t *peer_index); + +// Remove the given peer from the network interface +err_t wireguardif_remove_peer(struct netif *netif, u8_t peer_index); + +// Update the "connect" IP of the given peer +err_t wireguardif_update_endpoint(struct netif *netif, u8_t peer_index, const ip_addr_t *ip, u16_t port); + +// Try and connect to the given peer +err_t wireguardif_connect(struct netif *netif, u8_t peer_index); + +// Stop trying to connect to the given peer +err_t wireguardif_disconnect(struct netif *netif, u8_t peer_index); + +// Is the given peer "up"? A peer is up if it has a valid session key it can communicate with +err_t wireguardif_peer_is_up(struct netif *netif, u8_t peer_index, ip_addr_t *current_ip, u16_t *current_port); + +#endif /* _WIREGUARDIF_H_ */ From 3789d446bd3c4ec18731b0e1ce025df04b4ec245 Mon Sep 17 00:00:00 2001 From: Jaroslav Kysela Date: Thu, 30 Nov 2023 15:25:09 +0100 Subject: [PATCH 2/3] fix some warnings in the wireguard library --- lib/WireGuard-ESP32/src/wireguard.h | 1 + lib/WireGuard-ESP32/src/wireguardif.c | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/WireGuard-ESP32/src/wireguard.h b/lib/WireGuard-ESP32/src/wireguard.h index 961792a09..d5554926d 100644 --- a/lib/WireGuard-ESP32/src/wireguard.h +++ b/lib/WireGuard-ESP32/src/wireguard.h @@ -272,6 +272,7 @@ bool wireguard_create_handshake_initiation(struct wireguard_device *device, stru bool wireguard_create_handshake_response(struct wireguard_device *device, struct wireguard_peer *peer, struct message_handshake_response *dst); void wireguard_create_cookie_reply(struct wireguard_device *device, struct message_cookie_reply *dst, const uint8_t *mac1, uint32_t index, uint8_t *source_addr_port, size_t source_length); +void handshake_destroy(struct wireguard_handshake *handshake); bool wireguard_check_mac1(struct wireguard_device *device, const uint8_t *data, size_t len, const uint8_t *mac1); bool wireguard_check_mac2(struct wireguard_device *device, const uint8_t *data, size_t len, uint8_t *source_addr_port, size_t source_length, const uint8_t *mac2); diff --git a/lib/WireGuard-ESP32/src/wireguardif.c b/lib/WireGuard-ESP32/src/wireguardif.c index d64ad8548..c8192f629 100644 --- a/lib/WireGuard-ESP32/src/wireguardif.c +++ b/lib/WireGuard-ESP32/src/wireguardif.c @@ -48,7 +48,7 @@ #include "wireguard.h" #include "crypto.h" #include "esp_log.h" -#include "tcpip_adapter.h" +#include "esp_netif.h" #include "esp32-hal-log.h" @@ -921,7 +921,7 @@ err_t wireguardif_init(struct netif *netif) { size_t private_key_len = sizeof(private_key); struct netif* underlying_netif; - tcpip_adapter_get_netif(TCPIP_ADAPTER_IF_STA, &underlying_netif); + tcpip_adapter_get_netif(TCPIP_ADAPTER_IF_STA, (void **)&underlying_netif); log_i(TAG "underlying_netif = %p", underlying_netif); LWIP_ASSERT("netif != NULL", (netif != NULL)); From 2c94573edb7226ce510674f1e04e8142e6df9a0b Mon Sep 17 00:00:00 2001 From: Jaroslav Kysela Date: Wed, 29 Nov 2023 20:41:28 +0100 Subject: [PATCH 3/3] add WireGuard implementation to increase security WireGuard is really ideal for those IoT devices with limited resources. --- data/en.json | 2 +- data/main.js | 2 +- include/hasp_conf.h | 8 ++ src/hasp/hasp_dispatch.cpp | 8 ++ src/hasp/hasp_nvs.cpp | 37 ++++++--- src/hasp_config.cpp | 51 +++++++++++-- src/hasp_config.h | 5 ++ src/hasp_debug.cpp | 4 + src/hasp_debug.h | 1 + src/lang/en_US.h | 7 ++ src/sys/net/hasp_network.cpp | 31 ++++++++ src/sys/net/hasp_network.h | 1 + src/sys/net/hasp_wireguard.cpp | 131 ++++++++++++++++++++++++++++++++ src/sys/net/hasp_wireguard.h | 40 ++++++++++ src/sys/svc/hasp_http.cpp | 75 ++++++++++++++++++ src/sys/svc/hasp_http_async.cpp | 2 +- 16 files changed, 384 insertions(+), 21 deletions(-) create mode 100644 src/sys/net/hasp_wireguard.cpp create mode 100644 src/sys/net/hasp_wireguard.h diff --git a/data/en.json b/data/en.json index 0bfe12d41..248e4adcd 100644 --- a/data/en.json +++ b/data/en.json @@ -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 "}}} \ No newline at end of file +{"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 "}}} \ No newline at end of file diff --git a/data/main.js b/data/main.js index a74ef0c94..989d9086c 100644 --- a/data/main.js +++ b/data/main.js @@ -1 +1 @@ -import{createApp,reactive,createI18n}from"/static/petite-vue.hasp.js?COMMIT_HASH";const languages=[{code:"en",name:"English"},{code:"nl",name:"Nederlands"},{code:"fr",name:"Français"}];var locations={af:["Abidjan","Algiers","Bissau","Cairo","Casablanca","El_Aaiun","Johannesburg","Juba","Khartoum","Lagos","Maputo","Monrovia","Nairobi","Ndjamena","Sao_Tome","Tripoli","Tunis","Windhoek","Cape_Verde","Mauritius"],eu:["Ceuta","Danmarkshavn","Nuuk","Scoresbysund","Thule","Anadyr","Barnaul","Chita","Irkutsk","Kamchatka","Khandyga","Krasnoyarsk","Magadan","Novokuznetsk","Novosibirsk","Omsk","Sakhalin","Srednekolymsk","Tomsk","Ust-Nera","Vladivostok","Yakutsk","Yekaterinburg","Azores","Canary","Faroe","Madeira","Andorra","Astrakhan","Athens","Belgrade","Berlin","Brussels","Bucharest","Budapest","Chisinau","Dublin","Gibraltar","Helsinki","Istanbul","Kaliningrad","Kirov","Kyiv","Lisbon","London","Madrid","Malta","Minsk","Moscow","Paris","Prague","Riga","Rome","Samara","Saratov","Sofia","Tallinn","Tirane","Ulyanovsk","Vienna","Vilnius","Volgograd","Warsaw","Zurich"],as:["Almaty","Amman","Aqtau","Aqtobe","Ashgabat","Atyrau","Baghdad","Baku","Bangkok","Beirut","Bishkek","Choibalsan","Colombo","Damascus","Dhaka","Dili","Dubai","Dushanbe","Famagusta","Gaza","Hebron","Ho_Chi_Minh","Hong_Kong","Hovd","Jakarta","Jayapura","Jerusalem","Kabul","Karachi","Kathmandu","Kolkata","Kuching","Macau","Makassar","Manila","Nicosia","Oral","Pontianak","Pyongyang","Qatar","Qostanay","Qyzylorda","Riyadh","Samarkand","Seoul","Shanghai","Singapore","Taipei","Tashkent","Tbilisi","Tehran","Thimphu","Tokyo","Ulaanbaatar","Urumqi","Yangon","Yerevan","Chagos","Maldives"],au:["Perth","Eucla","Adelaide","Broken_Hill","Darwin","Brisbane","Hobart","Lindeman","Melbourne","Sydney","Lord_Howe"],na:["Adak","Anchorage","Bahia_Banderas","Barbados","Belize","Boise","Cambridge_Bay","Cancun","Chicago","Chihuahua","Ciudad_Juarez","Costa_Rica","Dawson","Dawson_Creek","Denver","Detroit","Edmonton","El_Salvador","Fort_Nelson","Glace_Bay","Goose_Bay","Grand_Turk","Guatemala","Halifax","Havana","Hermosillo","Indiana/Indianapolis","Indiana/Knox","Indiana/Marengo","Indiana/Petersburg","Indiana/Tell_City","Indiana/Vevay","Indiana/Vincennes","Indiana/Winamac","Inuvik","Iqaluit","Jamaica","Juneau","Kentucky/Louisville","Kentucky/Monticello","Los_Angeles","Managua","Martinique","Matamoros","Mazatlan","Menominee","Merida","Metlakatla","Mexico_City","Miquelon","Moncton","Monterrey","New_York","Nome","North_Dakota/Beulah","North_Dakota/Center","North_Dakota/New_Salem","Ojinaga","Panama","Phoenix","Port-au-Prince","Puerto_Rico","Rankin_Inlet","Regina","Resolute","Santo_Domingo","Sitka","St_Johns","Swift_Current","Tegucigalpa","Tijuana","Toronto","Vancouver","Whitehorse","Winnipeg","Yakutat","Yellowknife","Bermuda","Honolulu"],sa:["Araguaina","Argentina/Buenos_Aires","Argentina/Catamarca","Argentina/Cordoba","Argentina/Jujuy","Argentina/La_Rioja","Argentina/Mendoza","Argentina/Rio_Gallegos","Argentina/Salta","Argentina/San_Juan","Argentina/San_Luis","Argentina/Tucuman","Argentina/Ushuaia","Asuncion","Bahia","Belem","Boa_Vista","Bogota","Campo_Grande","Caracas","Cayenne","Cuiaba","Eirunepe","Fortaleza","Guayaquil","Guyana","La_Paz","Lima","Maceio","Manaus","Montevideo","Noronha","Paramaribo","Porto_Velho","Punta_Arenas","Recife","Rio_Branco","Santarem","Santiago","Sao_Paulo","Palmer","South_Georgia","Stanley","Easter","Galapagos"],at:["Cape_Verde","Canary","Faroe","Madeira","Azores","Bermuda","South_Georgia","Stanley"],in:["Mauritius","Maldives","Chagos"],pa:["Palau","Guam","Port_Moresby","Bougainville","Efate","Guadalcanal","Kosrae","Norfolk","Noumea","Auckland","Fiji","Kwajalein","Nauru","Tarawa","Chatham","Apia","Fakaofo","Kanton","Tongatapu","Kiritimati","Pitcairn","Gambier","Marquesas","Rarotonga","Tahiti","Niue","Pago_Pago","Honolulu","Easter","Galapagos"],aq:["Troll","Mawson","Davis","Casey","Rothera","Macquarie","Palmer"],etc:["Greenwich","Universal","Zulu","GMT-14","GMT-13","GMT-12","GMT-11","GMT-10","GMT-9","GMT-8","GMT-7","GMT-6","GMT-5","GMT-4","GMT-3","GMT-2","GMT-1","GMT","GMT+1","GMT+2","GMT+3","GMT+4","GMT+5","GMT+6","GMT+7","GMT+8","GMT+9","GMT+10","GMT+11","GMT+12","UCT","UTC"]};const regions={etc:"Etc",af:"Africa",as:"Asia",au:"Australia",aq:"Antarctica",eu:"Europe",na:"America",sa:"America",at:"Atlantic",in:"Indian",pa:"Pacific"},licenseData=[],licenseApp=[{t:"Petite Vue",y:2021,a:"Yuxi (Evan) You",l:"mit"},{t:"Petite Vue I18n Lite",y:2021,a:"Front Labs",l:"mit"},{t:"Ace Editor",y:2010,a:"Ajax.org B.V.",r:1,l:"bsd"},{t:"MaterialDesign Icons",y:2022,a:"Google",l:"apache2"}];function Credits(a){return{$template:"#credit-template",model:a}}function RegionItem(a,o,e){return{$template:"#region-template",model:a,region:o,i18n:e,list(e){if(a[e]&&o[e]){for(var n="etc"===e?a[e]:a[e].sort(),t=[],i=0;ie.t(a).toString().replace(/_/g," ")}}fetch("/static/en.json?COMMIT_HASH").then((a=>a.json())).then((a=>{const o=reactive(createI18n({locale:"en",fallbackLocale:"en",messages:{en:a.en}}));createApp({i18n:o,languages:languages,RegionItem:RegionItem,regions:regions,locations:locations,licenseData:licenseData,licenseApp:licenseApp,Credits:Credits,hostname:null,title:null,config:{hasp:null,wifi:null,mqtt:null,http:null,gui:null,gpio:null,debug:null,time:null,ota:null},info:null,files:null,show:null,t(a){return this.i18n.t(a)},fetchConfig(a){fetch("/api/config/"+a+"/").then((a=>a.json())).then((o=>{this.config[a]=o,this.show=a,document.title=a}))},submitConfig(){let a=this.show;fetch("/api/config/"+a+"/",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(this.config[a])}).then((a=>a.json())).then((o=>{this.config[a]=o,window.history.pushState({},"","/config/"),window.dispatchEvent(new Event("popstate"))}))},submitOldConfig(a){fetch("/api/config/"+a+"/",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(this.config[a])}).then((a=>a.json())).then((a=>{window.location.href="/config"}))},fetchLang(a){fetch("/static/"+a+".json?COMMIT_HASH").then((a=>a.json())).then((o=>{let e=o[a]?o[a]:{};this.i18n.setLocaleMessage(a,e),this.i18n.changeLocale(a),console.log(a)}))},fetchInfo(){fetch("/api/info/").then((a=>a.json())).then((a=>{this.info=a,this.show="info",document.title="Info"}))},fetchAbout(){fetch("/api/credits/").then((a=>a.json())).then((a=>{this.licenseData=a,this.show="about",document.title="About"}))},showPage(a){console.log("showPage "+a),this.show=a,document.title=a,""!=a&&(a+="/")},showInfo(){console.log("showInfo"),this.fetchInfo(),document.title="Info"},showConfig(a){console.log("showConfig "+a),this.fetchConfig(a),document.title=a},showEditor(){console.log("showEditor"),fetch("/api/files/").then((a=>a.json())).then((a=>{this.files=a,this.show="edit";var o=document.getElementsByClassName("container__editor")[0];o&&(o.style.display="flex"),document.title="Editor"}))},handleLocation(a,o){const e={"/":()=>{this.showPage("")},"/hasp.htm":()=>{this.showPage("")},"/config/":()=>{this.showPage("config")},"/config/hasp/":()=>{this.showConfig("hasp")},"/config/wifi/":()=>{this.showConfig("wifi")},"/config/http/":()=>{this.showConfig("http")},"/config/mqtt/":()=>{this.showConfig("mqtt")},"/config/gui/":()=>{this.showConfig("gui")},"/config/ftp/":()=>{this.showConfig("ftp")},"/config/time/":()=>{this.showConfig("time")},"/config/debug/":()=>{this.showConfig("debug")},"/config/reset/":()=>{this.showPage("reset")},"/firmware/":()=>{this.showConfig("ota")},"/info/":()=>{this.showInfo()},"/screenshot/":()=>{this.showPage("screenshot")},"/about/":()=>{this.fetchAbout()},"/edit/":()=>{this.showEditor()},"/edit":()=>{},"/static/editor.htm":()=>{},"/reboot/":()=>{this.showPage("reboot")}};"function"==typeof e[a]?(console.log("Location: "+a),e[a]()):"/"!==a.slice(-1)&&"function"==typeof e[a+"/"]?(console.log("Location: "+a),e[a+"/"]()):(console.log("Not found: "+a),e["/"]);const n=document.getElementsByClassName("container__editor")[0];n&&(n.style.display=a.includes("/edit")?"flex":"none"),window.scrollTo({top:o})},mounted(){let a=decodeURIComponent(document.cookie).split(";");for(let o=0;o{const o=window.location.pathname;console.log("Popstate: "+o),console.log(a);var e=a.state,n=0;e&&(n=e.scrollTop),this.handleLocation(o,n)};const o=window.location.pathname;this.handleLocation(o,0),console.log("App Mounted")},route(a){console.log("Routing..."),a=a||window.event,console.log(a.target),a.preventDefault();const o=a.currentTarget.href||a.target.parentNode.href,e=new URL(o).pathname;if(window.location.pathname!=e){console.log("Push Route: "+e);var n={path:window.location.href||a.target.href,scrollTop:document.body.scrollTop};window.history.replaceState(n,"",document.location.pathname),n={path:window.location.href,scrollTop:0},window.history.pushState(n,"",e),window.dispatchEvent(new Event("popstate"))}},goto(a){if(console.log("Goto..."),window.location.pathname!=a){console.log("Push Route: "+a);var o={path:window.location.href,scrollTop:document.body.scrollTop};window.history.replaceState(o,"",document.location.pathname),o={path:window.location.href,scrollTop:0},window.history.pushState(o,"",a),window.dispatchEvent(new Event("popstate"))}},ref(a){},aref(a){setTimeout((function(){}),1e3*a)},upd(a){var o=(new Date).getTime();document.getElementById("bmp").src="/screenshot?a="+a+"&q="+o}}).directive("t",(({el:a,get:e,effect:n})=>n((()=>a.textContent=o.t(e()))))).directive("ts",(({el:a,get:e,effect:n})=>n((()=>a.textContent=o.t(e()).replace(/_/g," "))))).mount(),console.log("JS Loaded...")})); \ No newline at end of file +import{createApp,reactive,createI18n}from"/static/petite-vue.hasp.js?COMMIT_HASH";const languages=[{code:"en",name:"English"},{code:"nl",name:"Nederlands"},{code:"fr",name:"Français"}];var locations={af:["Abidjan","Algiers","Bissau","Cairo","Casablanca","El_Aaiun","Johannesburg","Juba","Khartoum","Lagos","Maputo","Monrovia","Nairobi","Ndjamena","Sao_Tome","Tripoli","Tunis","Windhoek","Cape_Verde","Mauritius"],eu:["Ceuta","Danmarkshavn","Nuuk","Scoresbysund","Thule","Anadyr","Barnaul","Chita","Irkutsk","Kamchatka","Khandyga","Krasnoyarsk","Magadan","Novokuznetsk","Novosibirsk","Omsk","Sakhalin","Srednekolymsk","Tomsk","Ust-Nera","Vladivostok","Yakutsk","Yekaterinburg","Azores","Canary","Faroe","Madeira","Andorra","Astrakhan","Athens","Belgrade","Berlin","Brussels","Bucharest","Budapest","Chisinau","Dublin","Gibraltar","Helsinki","Istanbul","Kaliningrad","Kirov","Kyiv","Lisbon","London","Madrid","Malta","Minsk","Moscow","Paris","Prague","Riga","Rome","Samara","Saratov","Sofia","Tallinn","Tirane","Ulyanovsk","Vienna","Vilnius","Volgograd","Warsaw","Zurich"],as:["Almaty","Amman","Aqtau","Aqtobe","Ashgabat","Atyrau","Baghdad","Baku","Bangkok","Beirut","Bishkek","Choibalsan","Colombo","Damascus","Dhaka","Dili","Dubai","Dushanbe","Famagusta","Gaza","Hebron","Ho_Chi_Minh","Hong_Kong","Hovd","Jakarta","Jayapura","Jerusalem","Kabul","Karachi","Kathmandu","Kolkata","Kuching","Macau","Makassar","Manila","Nicosia","Oral","Pontianak","Pyongyang","Qatar","Qostanay","Qyzylorda","Riyadh","Samarkand","Seoul","Shanghai","Singapore","Taipei","Tashkent","Tbilisi","Tehran","Thimphu","Tokyo","Ulaanbaatar","Urumqi","Yangon","Yerevan","Chagos","Maldives"],au:["Perth","Eucla","Adelaide","Broken_Hill","Darwin","Brisbane","Hobart","Lindeman","Melbourne","Sydney","Lord_Howe"],na:["Adak","Anchorage","Bahia_Banderas","Barbados","Belize","Boise","Cambridge_Bay","Cancun","Chicago","Chihuahua","Ciudad_Juarez","Costa_Rica","Dawson","Dawson_Creek","Denver","Detroit","Edmonton","El_Salvador","Fort_Nelson","Glace_Bay","Goose_Bay","Grand_Turk","Guatemala","Halifax","Havana","Hermosillo","Indiana/Indianapolis","Indiana/Knox","Indiana/Marengo","Indiana/Petersburg","Indiana/Tell_City","Indiana/Vevay","Indiana/Vincennes","Indiana/Winamac","Inuvik","Iqaluit","Jamaica","Juneau","Kentucky/Louisville","Kentucky/Monticello","Los_Angeles","Managua","Martinique","Matamoros","Mazatlan","Menominee","Merida","Metlakatla","Mexico_City","Miquelon","Moncton","Monterrey","New_York","Nome","North_Dakota/Beulah","North_Dakota/Center","North_Dakota/New_Salem","Ojinaga","Panama","Phoenix","Port-au-Prince","Puerto_Rico","Rankin_Inlet","Regina","Resolute","Santo_Domingo","Sitka","St_Johns","Swift_Current","Tegucigalpa","Tijuana","Toronto","Vancouver","Whitehorse","Winnipeg","Yakutat","Yellowknife","Bermuda","Honolulu"],sa:["Araguaina","Argentina/Buenos_Aires","Argentina/Catamarca","Argentina/Cordoba","Argentina/Jujuy","Argentina/La_Rioja","Argentina/Mendoza","Argentina/Rio_Gallegos","Argentina/Salta","Argentina/San_Juan","Argentina/San_Luis","Argentina/Tucuman","Argentina/Ushuaia","Asuncion","Bahia","Belem","Boa_Vista","Bogota","Campo_Grande","Caracas","Cayenne","Cuiaba","Eirunepe","Fortaleza","Guayaquil","Guyana","La_Paz","Lima","Maceio","Manaus","Montevideo","Noronha","Paramaribo","Porto_Velho","Punta_Arenas","Recife","Rio_Branco","Santarem","Santiago","Sao_Paulo","Palmer","South_Georgia","Stanley","Easter","Galapagos"],at:["Cape_Verde","Canary","Faroe","Madeira","Azores","Bermuda","South_Georgia","Stanley"],in:["Mauritius","Maldives","Chagos"],pa:["Palau","Guam","Port_Moresby","Bougainville","Efate","Guadalcanal","Kosrae","Norfolk","Noumea","Auckland","Fiji","Kwajalein","Nauru","Tarawa","Chatham","Apia","Fakaofo","Kanton","Tongatapu","Kiritimati","Pitcairn","Gambier","Marquesas","Rarotonga","Tahiti","Niue","Pago_Pago","Honolulu","Easter","Galapagos"],aq:["Troll","Mawson","Davis","Casey","Rothera","Macquarie","Palmer"],etc:["Greenwich","Universal","Zulu","GMT-14","GMT-13","GMT-12","GMT-11","GMT-10","GMT-9","GMT-8","GMT-7","GMT-6","GMT-5","GMT-4","GMT-3","GMT-2","GMT-1","GMT","GMT+1","GMT+2","GMT+3","GMT+4","GMT+5","GMT+6","GMT+7","GMT+8","GMT+9","GMT+10","GMT+11","GMT+12","UCT","UTC"]};const regions={etc:"Etc",af:"Africa",as:"Asia",au:"Australia",aq:"Antarctica",eu:"Europe",na:"America",sa:"America",at:"Atlantic",in:"Indian",pa:"Pacific"},licenseData=[],licenseApp=[{t:"Petite Vue",y:2021,a:"Yuxi (Evan) You",l:"mit"},{t:"Petite Vue I18n Lite",y:2021,a:"Front Labs",l:"mit"},{t:"Ace Editor",y:2010,a:"Ajax.org B.V.",r:1,l:"bsd"},{t:"MaterialDesign Icons",y:2022,a:"Google",l:"apache2"}];function Credits(a){return{$template:"#credit-template",model:a}}function RegionItem(a,o,e){return{$template:"#region-template",model:a,region:o,i18n:e,list(e){if(a[e]&&o[e]){for(var n="etc"===e?a[e]:a[e].sort(),t=[],i=0;ie.t(a).toString().replace(/_/g," ")}}fetch("/static/en.json?COMMIT_HASH").then((a=>a.json())).then((a=>{const o=reactive(createI18n({locale:"en",fallbackLocale:"en",messages:{en:a.en}}));createApp({i18n:o,languages:languages,RegionItem:RegionItem,regions:regions,locations:locations,licenseData:licenseData,licenseApp:licenseApp,Credits:Credits,hostname:null,title:null,config:{hasp:null,wifi:null,wg:null,mqtt:null,http:null,gui:null,gpio:null,debug:null,time:null,ota:null},info:null,files:null,show:null,t(a){return this.i18n.t(a)},fetchConfig(a){fetch("/api/config/"+a+"/").then((a=>a.json())).then((o=>{this.config[a]=o,this.show=a,document.title=a}))},submitConfig(){let a=this.show;fetch("/api/config/"+a+"/",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(this.config[a])}).then((a=>a.json())).then((o=>{this.config[a]=o,window.history.pushState({},"","/config/"),window.dispatchEvent(new Event("popstate"))}))},submitOldConfig(a){fetch("/api/config/"+a+"/",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(this.config[a])}).then((a=>a.json())).then((a=>{window.location.href="/config"}))},fetchLang(a){fetch("/static/"+a+".json?COMMIT_HASH").then((a=>a.json())).then((o=>{let e=o[a]?o[a]:{};this.i18n.setLocaleMessage(a,e),this.i18n.changeLocale(a),console.log(a)}))},fetchInfo(){fetch("/api/info/").then((a=>a.json())).then((a=>{this.info=a,this.show="info",document.title="Info"}))},fetchAbout(){fetch("/api/credits/").then((a=>a.json())).then((a=>{this.licenseData=a,this.show="about",document.title="About"}))},showPage(a){console.log("showPage "+a),this.show=a,document.title=a,""!=a&&(a+="/")},showInfo(){console.log("showInfo"),this.fetchInfo(),document.title="Info"},showConfig(a){console.log("showConfig "+a),this.fetchConfig(a),document.title=a},showEditor(){console.log("showEditor"),fetch("/api/files/").then((a=>a.json())).then((a=>{this.files=a,this.show="edit";var o=document.getElementsByClassName("container__editor")[0];o&&(o.style.display="flex"),document.title="Editor"}))},handleLocation(a,o){const e={"/":()=>{this.showPage("")},"/hasp.htm":()=>{this.showPage("")},"/config/":()=>{this.showPage("config")},"/config/hasp/":()=>{this.showConfig("hasp")},"/config/wifi/":()=>{this.showConfig("wifi")},"/config/wg/":()=>{this.showConfig("wg")},"/config/http/":()=>{this.showConfig("http")},"/config/mqtt/":()=>{this.showConfig("mqtt")},"/config/gui/":()=>{this.showConfig("gui")},"/config/ftp/":()=>{this.showConfig("ftp")},"/config/time/":()=>{this.showConfig("time")},"/config/debug/":()=>{this.showConfig("debug")},"/config/reset/":()=>{this.showPage("reset")},"/firmware/":()=>{this.showConfig("ota")},"/info/":()=>{this.showInfo()},"/screenshot/":()=>{this.showPage("screenshot")},"/about/":()=>{this.fetchAbout()},"/edit/":()=>{this.showEditor()},"/edit":()=>{},"/static/editor.htm":()=>{},"/reboot/":()=>{this.showPage("reboot")}};"function"==typeof e[a]?(console.log("Location: "+a),e[a]()):"/"!==a.slice(-1)&&"function"==typeof e[a+"/"]?(console.log("Location: "+a),e[a+"/"]()):(console.log("Not found: "+a),e["/"]);const n=document.getElementsByClassName("container__editor")[0];n&&(n.style.display=a.includes("/edit")?"flex":"none"),window.scrollTo({top:o})},mounted(){let a=decodeURIComponent(document.cookie).split(";");for(let o=0;o{const o=window.location.pathname;console.log("Popstate: "+o),console.log(a);var e=a.state,n=0;e&&(n=e.scrollTop),this.handleLocation(o,n)};const o=window.location.pathname;this.handleLocation(o,0),console.log("App Mounted")},route(a){console.log("Routing..."),a=a||window.event,console.log(a.target),a.preventDefault();const o=a.currentTarget.href||a.target.parentNode.href,e=new URL(o).pathname;if(window.location.pathname!=e){console.log("Push Route: "+e);var n={path:window.location.href||a.target.href,scrollTop:document.body.scrollTop};window.history.replaceState(n,"",document.location.pathname),n={path:window.location.href,scrollTop:0},window.history.pushState(n,"",e),window.dispatchEvent(new Event("popstate"))}},goto(a){if(console.log("Goto..."),window.location.pathname!=a){console.log("Push Route: "+a);var o={path:window.location.href,scrollTop:document.body.scrollTop};window.history.replaceState(o,"",document.location.pathname),o={path:window.location.href,scrollTop:0},window.history.pushState(o,"",a),window.dispatchEvent(new Event("popstate"))}},ref(a){},aref(a){setTimeout((function(){}),1e3*a)},upd(a){var o=(new Date).getTime();document.getElementById("bmp").src="/screenshot?a="+a+"&q="+o}}).directive("t",(({el:a,get:e,effect:n})=>n((()=>a.textContent=o.t(e()))))).directive("ts",(({el:a,get:e,effect:n})=>n((()=>a.textContent=o.t(e()).replace(/_/g," "))))).mount(),console.log("JS Loaded...")})); \ No newline at end of file diff --git a/include/hasp_conf.h b/include/hasp_conf.h index 16a4ab238..448b66a35 100644 --- a/include/hasp_conf.h +++ b/include/hasp_conf.h @@ -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 @@ -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" diff --git a/src/hasp/hasp_dispatch.cpp b/src/hasp/hasp_dispatch.cpp index acbc97343..385482648 100644 --- a/src/hasp/hasp_dispatch.cpp +++ b/src/hasp/hasp_dispatch.cpp @@ -503,6 +503,14 @@ void dispatch_config(const char* topic, const char* payload, uint8_t source) else timeGetConfig(settings); } +#if HASP_USE_WIREGUARD > 0 + else if(strcasecmp_P(topic, PSTR(FP_WG)) == 0) { + if(update) + wgSetConfig(settings); + else + wgGetConfig(settings); + } +#endif #if HASP_USE_MQTT > 0 else if(strcasecmp_P(topic, PSTR(FP_MQTT)) == 0) { if(update) diff --git a/src/hasp/hasp_nvs.cpp b/src/hasp/hasp_nvs.cpp index 439a1beae..a2fd0b230 100644 --- a/src/hasp/hasp_nvs.cpp +++ b/src/hasp/hasp_nvs.cpp @@ -6,6 +6,8 @@ #include "hasplib.h" #include "hasp_nvs.h" +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) + bool nvs_user_begin(Preferences& preferences, const char* key, bool readonly) { if(preferences.begin(key, false, "config")) { @@ -22,16 +24,16 @@ bool nvs_user_begin(Preferences& preferences, const char* key, bool readonly) bool nvs_clear_user_config() { - const char* name[] = {FP_TIME, FP_OTA, FP_HTTP, FP_FTP, FP_MQTT, FP_WIFI}; + const char* name[] = {FP_TIME, FP_OTA, FP_HTTP, FP_FTP, FP_MQTT, FP_WIFI, FP_WG}; Preferences preferences; bool state = true; - for(int i = 0; i < sizeof(name) / sizeof(name[0]); i++) { + for(int i = 0; i < ARRAY_SIZE(name); i++) { if(preferences.begin(name[i], false) && !preferences.clear()) state = false; preferences.end(); } - for(int i = 0; i < sizeof(name) / sizeof(name[0]); i++) { + for(int i = 0; i < ARRAY_SIZE(name); i++) { if(preferences.begin(name[i], false, "config") && !preferences.clear()) state = false; preferences.end(); } @@ -226,19 +228,30 @@ void nvs_setup() nvs_stats.free_entries, nvs_stats.total_entries); { // TODO: remove migratrion of keys from default NVS partition to CONFIG partition - const char* name[8] = {FP_TIME, FP_OTA, FP_HTTP, FP_FTP, FP_MQTT, FP_WIFI}; + const struct { + const char* name; + const char* config; + } sec[] = { + { .name = FP_TIME, .config = FP_CONFIG_PASS }, + { .name = FP_OTA, .config = FP_CONFIG_PASS }, + { .name = FP_HTTP, .config = FP_CONFIG_PASS }, + { .name = FP_FTP, .config = FP_CONFIG_PASS }, + { .name = FP_MQTT, .config = FP_CONFIG_PASS }, + { .name = FP_WIFI, .config = FP_CONFIG_PASS }, + { .name = FP_WG, .config = FP_CONFIG_PRIVATE_KEY } + }; Preferences oldPrefs, newPrefs; - for(int i = 0; i < 6; i++) { - if(oldPrefs.begin(name[i], false) && newPrefs.begin(name[i], false, "config")) { - LOG_INFO(TAG_NVS, "opened %s", name[i]); - String password = oldPrefs.getString(FP_CONFIG_PASS, D_PASSWORD_MASK); + for(int i = 0; i < ARRAY_SIZE(sec); i++) { + if(oldPrefs.begin(sec[i].name, false) && newPrefs.begin(sec[i].name, false, "config")) { + LOG_INFO(TAG_NVS, "opened %s", sec[i].name); + String password = oldPrefs.getString(sec[i].config, D_PASSWORD_MASK); if(password != D_PASSWORD_MASK) { - LOG_INFO(TAG_NVS, "found %s %s => %s", name[i], D_PASSWORD_MASK, password.c_str()); - size_t len = newPrefs.putString(FP_CONFIG_PASS, password); + LOG_INFO(TAG_NVS, "found %s %s => %s", sec[i].name, D_PASSWORD_MASK, password.c_str()); + size_t len = newPrefs.putString(sec[i].config, password); if(len == password.length()) { - oldPrefs.remove(FP_CONFIG_PASS); - LOG_INFO(TAG_NVS, "Moved %s key %s to new NVS partition", name[i], FP_CONFIG_PASS); + oldPrefs.remove(sec[i].config); + LOG_INFO(TAG_NVS, "Moved %s key %s to new NVS partition", sec[i].name, sec[i].config); } } } diff --git a/src/hasp_config.cpp b/src/hasp_config.cpp index 9e3f5ce52..09ceea053 100644 --- a/src/hasp_config.cpp +++ b/src/hasp_config.cpp @@ -117,6 +117,19 @@ bool configSet(lv_color_t& value, const JsonVariant& setting, const __FlashStrin } return false; } +bool configSet(char *value, size_t size, const JsonVariant& setting, const __FlashStringHelper* fstr_name) +{ + if(!setting.isNull()) { + const char *val = setting; + if(strcmp(value, val) != 0) { + confDebugSet(fstr_name); + strncpy(value, val, size - 1); + value[size - 1] = '\0'; + return true; + } + } + return false; +} bool configSet(bool& value, const JsonVariant& setting, const char* fstr_name) { @@ -198,28 +211,30 @@ void configSetupDebug(JsonDocument& settings) debugStart(); // Debug started, now we can use it; HASP header sent } -void configStorePasswords(JsonDocument& settings, String& wifiPass, String& mqttPass, String& httpPass) +void configStorePasswords(JsonDocument& settings, String& wifiPass, String& mqttPass, String& httpPass, String &wgPrivKey) { const char* pass = ("pass"); wifiPass = settings[FPSTR(FP_WIFI)][pass].as(); mqttPass = settings[FPSTR(FP_MQTT)][pass].as(); httpPass = settings[FPSTR(FP_HTTP)][pass].as(); + wgPrivKey = settings[FPSTR(FP_WG)][FPSTR(FP_CONFIG_PRIVATE_KEY)].as(); } -void configRestorePasswords(JsonDocument& settings, String& wifiPass, String& mqttPass, String& httpPass) +void configRestorePasswords(JsonDocument& settings, String& wifiPass, String& mqttPass, String& httpPass, String& wgPrivKey) { const char* pass = ("pass"); if(!settings[FPSTR(FP_WIFI)][pass].isNull()) settings[FPSTR(FP_WIFI)][pass] = wifiPass; if(!settings[FPSTR(FP_MQTT)][pass].isNull()) settings[FPSTR(FP_MQTT)][pass] = mqttPass; if(!settings[FPSTR(FP_HTTP)][pass].isNull()) settings[FPSTR(FP_HTTP)][pass] = httpPass; + if(!settings[FPSTR(FP_WG)][FPSTR(FP_CONFIG_PRIVATE_KEY)].isNull()) settings[FPSTR(FP_WG)][FPSTR(FP_CONFIG_PRIVATE_KEY)] = wgPrivKey; } void configMaskPasswords(JsonDocument& settings) { String passmask = F(D_PASSWORD_MASK); - configRestorePasswords(settings, passmask, passmask, passmask); + configRestorePasswords(settings, passmask, passmask, passmask, passmask); } DeserializationError configParseFile(String& configFile, JsonDocument& settings) @@ -254,7 +269,7 @@ DeserializationError configRead(JsonDocument& settings, bool setupdebug) #if HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0 error = configParseFile(configFile, settings); if(!error) { - String output, wifiPass, mqttPass, httpPass; + String output, wifiPass, mqttPass, httpPass, wgPrivKey; /* Load Debug params */ if(setupdebug) { @@ -266,14 +281,14 @@ DeserializationError configRead(JsonDocument& settings, bool setupdebug) } LOG_TRACE(TAG_CONF, F(D_FILE_LOADING), configFile.c_str()); - configStorePasswords(settings, wifiPass, mqttPass, httpPass); + configStorePasswords(settings, wifiPass, mqttPass, httpPass, wgPrivKey); // Output settings in log with masked passwords configMaskPasswords(settings); serializeJson(settings, output); LOG_VERBOSE(TAG_CONF, output.c_str()); - configRestorePasswords(settings, wifiPass, mqttPass, httpPass); + configRestorePasswords(settings, wifiPass, mqttPass, httpPass, wgPrivKey); LOG_INFO(TAG_CONF, F(D_FILE_LOADED), configFile.c_str()); // if(setupdebug) debugSetup(); @@ -382,6 +397,17 @@ void configWrite() } #endif +#if HASP_USE_WIREGUARD > 0 + module = FPSTR(FP_WG); + if(settings[module].as().isNull()) settings.createNestedObject(module); + changed = wgGetConfig(settings[module]); + if(changed) { + LOG_VERBOSE(TAG_WG, settingsChanged.c_str()); + configOutput(settings[module], TAG_WG); + writefile = true; + } +#endif + #if HASP_USE_MQTT > 0 module = FPSTR(FP_MQTT); if(settings[module].as().isNull()) settings.createNestedObject(module); @@ -549,6 +575,11 @@ void configSetup() wifiSetConfig(settings[FPSTR(FP_WIFI)]); #endif +#if HASP_USE_WIREGUARD > 0 + LOG_INFO(TAG_WG, F("Loading WireGuard settings")); + wgSetConfig(settings[FPSTR(FP_WG)]); +#endif + #if HASP_USE_MQTT > 0 LOG_INFO(TAG_MQTT, F("Loading MQTT settings")); mqttSetConfig(settings[FPSTR(FP_MQTT)]); @@ -624,6 +655,14 @@ void configOutput(const JsonObject& settings, uint8_t tag) output.replace(password, passmask); } + if(!settings[FPSTR(FP_WG)][FPSTR(FP_CONFIG_PRIVATE_KEY)].isNull()) { + password = F("\"privkey\":\""); + password += settings[FPSTR(FP_WG)][FPSTR(FP_CONFIG_PRIVATE_KEY)].as(); + password += F("\""); + passmask = F("\"privkey\":\"" D_PASSWORD_MASK "\""); + output.replace(password, passmask); + } + LOG_VERBOSE(tag, output.c_str()); } diff --git a/src/hasp_config.h b/src/hasp_config.h index df5474085..7effe4cdf 100644 --- a/src/hasp_config.h +++ b/src/hasp_config.h @@ -31,6 +31,7 @@ bool configSet(uint8_t& value, const JsonVariant& setting, const __FlashStringHe bool configSet(uint16_t& value, const JsonVariant& setting, const __FlashStringHelper* fstr_name); bool configSet(int32_t& value, const JsonVariant& setting, const __FlashStringHelper* fstr_name); bool configSet(lv_color_t& value, const JsonVariant& setting, const __FlashStringHelper* fstr_name); +bool configSet(char *value, size_t size, const JsonVariant& setting, const __FlashStringHelper* fstr_name); bool configSet(bool& value, const JsonVariant& setting, const char* fstr_name); bool configSet(int8_t& value, const JsonVariant& setting, const char* fstr_name); bool configSet(uint8_t& value, const JsonVariant& setting, const char* fstr_name); @@ -71,6 +72,9 @@ const char FP_CONFIG_BROADCAST_TOPIC[] PROGMEM = "broadcast_t"; const char FP_CONFIG_BAUD[] PROGMEM = "baud"; const char FP_CONFIG_LOG[] PROGMEM = "log"; const char FP_CONFIG_PROTOCOL[] PROGMEM = "proto"; +const char FP_CONFIG_VPN_IP[] PROGMEM = "vpnip"; +const char FP_CONFIG_PRIVATE_KEY[] PROGMEM = "privkey"; +const char FP_CONFIG_PUBLIC_KEY[] PROGMEM = "pubkey"; const char FP_GUI_ROTATION[] PROGMEM = "rotate"; const char FP_GUI_INVERT[] PROGMEM = "invert"; const char FP_GUI_TICKPERIOD[] PROGMEM = "tick"; @@ -89,6 +93,7 @@ const char FP_GPIO_CONFIG[] PROGMEM = "config"; const char FP_HASP_CONFIG_FILE[] PROGMEM = "/config.json"; const char FP_WIFI[] PROGMEM = "wifi"; +const char FP_WG[] PROGMEM = "wg"; const char FP_MQTT[] PROGMEM = "mqtt"; const char FP_HTTP[] PROGMEM = "http"; const char FP_FTP[] PROGMEM = "ftp"; diff --git a/src/hasp_debug.cpp b/src/hasp_debug.cpp index df523c19a..52977625a 100644 --- a/src/hasp_debug.cpp +++ b/src/hasp_debug.cpp @@ -321,6 +321,10 @@ void debug_get_tag(uint8_t tag, char* buffer) memcpy_P(buffer, PSTR("CUST"), 5); break; + case TAG_WG: + memcpy_P(buffer, PSTR("WG "), 5); + break; + default: memcpy_P(buffer, PSTR("----"), 5); break; diff --git a/src/hasp_debug.h b/src/hasp_debug.h index b805004e9..425a7d973 100644 --- a/src/hasp_debug.h +++ b/src/hasp_debug.h @@ -194,6 +194,7 @@ enum { TAG_FTP = 68, TAG_TIME = 69, TAG_NETW = 70, + TAG_WG = 71, TAG_LVGL = 90, TAG_LVFS = 91, diff --git a/src/lang/en_US.h b/src/lang/en_US.h index b24d806db..13df8dbc3 100644 --- a/src/lang/en_US.h +++ b/src/lang/en_US.h @@ -127,6 +127,7 @@ #define D_HTTP_HTTP_SETTINGS "HTTP Settings" #define D_HTTP_FTP_SETTINGS "FTP Settings" #define D_HTTP_WIFI_SETTINGS "Wifi Settings" +#define D_HTTP_WIREGUARD_SETTINGS "WireGuard Settings" #define D_HTTP_MQTT_SETTINGS "MQTT Settings" #define D_HTTP_GPIO_SETTINGS "GPIO Settings" #define D_HTTP_MDNS_SETTINGS "mDNS Settings" @@ -191,6 +192,7 @@ #define D_INFO_FAILED "Failed" #define D_INFO_ETHERNET "Ethernet" #define D_INFO_WIFI "Wifi" +#define D_INFO_WIREGUARD "WireGuard" #define D_INFO_LINK_SPEED "Link Speed" #define D_INFO_FULL_DUPLEX "Full Duplex" #define D_INFO_BSSID "BSSID" @@ -200,6 +202,8 @@ #define D_INFO_MAC_ADDRESS "MAC Address" #define D_INFO_GATEWAY "Gateway" #define D_INFO_DNS_SERVER "DNS Server" +#define D_INFO_ENDPOINT_IP "Endpoint IP" +#define D_INFO_ENDPOINT_PORT "Endpoint Port" #define D_OOBE_MSG "Tap the screen to setup WiFi or connect to this Access Point:" #define D_OOBE_SCAN_TO_CONNECT "Scan to connect" @@ -212,6 +216,9 @@ #define D_WIFI_RSSI_WEAK "Weak" #define D_WIFI_RSSI_BAD "Very bad" +#define D_WG_INITIALIZED "Initialized" +#define D_WG_BAD_CONFIG "Missing or bad configuration" + #define D_GPIO_SWITCH "Switch" #define D_GPIO_BUTTON "Push Button" #define D_GPIO_TOUCH "Capacitive Touch" diff --git a/src/sys/net/hasp_network.cpp b/src/sys/net/hasp_network.cpp index 5b20ad4ae..395f3a2f8 100644 --- a/src/sys/net/hasp_network.cpp +++ b/src/sys/net/hasp_network.cpp @@ -14,6 +14,11 @@ uint16_t network_reconnect_counter = 0; #if HASP_USE_ETHERNET > 0 || HASP_USE_WIFI > 0 +bool network_is_connected() +{ + return current_network_state; +} + void network_disconnected() { @@ -23,6 +28,9 @@ void network_disconnected() // if(!current_network_state) return; // we were not connected current_network_state = false; // now we are disconnected +#if HASP_USE_WIREGUARD + wg_network_disconnected(); +#endif network_reconnect_counter++; // LOG_VERBOSE(TAG_NETW, F("Connected = %s"), // WiFi.status() == WL_CONNECTED ? PSTR(D_NETWORK_ONLINE) : PSTR(D_NETWORK_OFFLINE)); @@ -32,10 +40,15 @@ void network_connected() { if(current_network_state) return; // already connected +#if HASP_USE_WIREGUARD + wg_network_connected(); +#endif + current_network_state = true; // now we are connected network_reconnect_counter = 0; LOG_VERBOSE(TAG_NETW, F("Connected = %s"), WiFi.status() == WL_CONNECTED ? PSTR(D_NETWORK_ONLINE) : PSTR(D_NETWORK_OFFLINE)); + } void network_run_scripts() @@ -101,6 +114,10 @@ void networkSetup() #if HASP_USE_WIFI > 0 wifiSetup(); #endif + +#if HASP_USE_WIREGUARD > 0 + wg_setup(); +#endif } IRAM_ATTR void networkLoop(void) @@ -178,10 +195,20 @@ void network_get_statusupdate(char* buffer, size_t len) #if HASP_USE_WIFI > 0 wifi_get_statusupdate(buffer, len); #endif + +#if HASP_USE_WIREGUARD > 0 + size_t l = strlen(buffer); + wg_get_statusupdate(buffer + l, len - l); +#endif } void network_get_ipaddress(char* buffer, size_t len) { +#if HASP_USE_WIREGUARD > 0 + if (wg_get_ipaddress(buffer, len)) + return; +#endif + #if HASP_USE_ETHERNET > 0 #if defined(ARDUINO_ARCH_ESP32) #if HASP_USE_ETHSPI > 0 @@ -222,6 +249,10 @@ void network_get_info(JsonDocument& doc) #if HASP_USE_WIFI > 0 wifi_get_info(doc); #endif + +#if HASP_USE_WIREGUARD > 0 + wg_get_info(doc); +#endif } #endif diff --git a/src/sys/net/hasp_network.h b/src/sys/net/hasp_network.h index 83f9b7b21..47ec456aa 100644 --- a/src/sys/net/hasp_network.h +++ b/src/sys/net/hasp_network.h @@ -11,6 +11,7 @@ bool networkEvery5Seconds(void); // bool networkEverySecond(void); void networkStart(void); void networkStop(void); +bool network_is_connected(); /* ===== Special Event Processors ===== */ void network_connected(); diff --git a/src/sys/net/hasp_wireguard.cpp b/src/sys/net/hasp_wireguard.cpp new file mode 100644 index 000000000..36b055151 --- /dev/null +++ b/src/sys/net/hasp_wireguard.cpp @@ -0,0 +1,131 @@ +/* MIT License - Copyright (c) 2023 Jaroslav Kysela + For full license information read the LICENSE file in the project folder */ + +#include "hasplib.h" + +#if HASP_USE_WIREGUARD > 0 + +#include "hal/hasp_hal.h" +#include "hasp_debug.h" +#include "hasp_network.h" +#include "WireGuard-ESP32.h" + +char wg_ip[16] = WIREGUARD_IP; +char wg_private_key[45] = WIREGUARD_PRIVATE_KEY; +char wg_ep_ip[16] = WIREGUARD_EP_IP; +uint16_t wg_ep_port = WIREGUARD_EP_PORT; +char wg_ep_public_key[45] = WIREGUARD_EP_PUBLIC_KEY; +static WireGuard wg; + +void wg_setup() +{ + Preferences preferences; + nvs_user_begin(preferences, FP_WG, true); + String privkey = preferences.getString(FP_CONFIG_PRIVATE_KEY, String(wg_private_key)); // Update from NVS if it exists + strncpy(wg_private_key, privkey.c_str(), sizeof(wg_private_key)-1); + wg_private_key[sizeof(wg_private_key)-1] = '\0'; +} + +int wg_config_valid() +{ + return strlen(wg_ip) > 7 && strlen(wg_ep_ip) > 7 && + strlen(wg_private_key) == 44 && strlen(wg_ep_public_key) == 44 && + wg_ep_port > 0; +} + +void wg_network_disconnected() +{ + wg.end(); +} + +void wg_network_connected() +{ + IPAddress local_ip; + LOG_VERBOSE(TAG_WG, F("WireGuard connected")); + if (local_ip.fromString(wg_ip) && wg_config_valid()) { + LOG_INFO(TAG_WG, F("WireGuard begin (%s -> %s:%u)"), wg_ip, wg_ep_ip, wg_ep_port); + wg.begin(local_ip, wg_private_key, wg_ep_ip, wg_ep_public_key, wg_ep_port); + } +} + +void wg_get_statusupdate(char* buffer, size_t len) +{ + snprintf_P(buffer, len, PSTR("\"wg\":\"%s\","), wg.is_initialized() ? "on" : "off"); +} + +int wg_get_ipaddress(char* buffer, size_t len) +{ + if (wg.is_initialized()) { + snprintf(buffer, len, "%s", wg_ip); + return 1; + } + return 0; +} + +void wg_get_info(JsonDocument& doc) +{ + JsonObject info = doc.createNestedObject(F(D_INFO_WIREGUARD)); + info[F(D_INFO_STATUS)] = wg.is_initialized() ? F(D_WG_INITIALIZED) : F(D_WG_BAD_CONFIG); + info[F(D_INFO_IP_ADDRESS)] = String(wg_ip); + info[F(D_INFO_ENDPOINT_IP)] = String(wg_ep_ip); + info[F(D_INFO_ENDPOINT_PORT)] = String(wg_ep_port); +} + +#if HASP_USE_CONFIG > 0 +bool wgGetConfig(const JsonObject& settings) +{ + bool changed = false; + + if(strcmp(wg_ip, settings[FPSTR(FP_CONFIG_VPN_IP)].as().c_str()) != 0) changed = true; + settings[FPSTR(FP_CONFIG_VPN_IP)] = wg_ip; + + if(strcmp(wg_private_key, settings[FPSTR(FP_CONFIG_PRIVATE_KEY)].as().c_str()) != 0) changed = true; + //settings[FPSTR(FP_CONFIG_PRIVATE_KEY)] = wg_private_key; + settings[FPSTR(FP_CONFIG_PRIVATE_KEY)] = D_PASSWORD_MASK; + + if(strcmp(wg_ep_ip, settings[FPSTR(FP_CONFIG_HOST)].as().c_str()) != 0) changed = true; + settings[FPSTR(FP_CONFIG_HOST)] = wg_ep_ip; + + if(wg_ep_port != settings[FPSTR(FP_CONFIG_PORT)].as()) changed = true; + settings[FPSTR(FP_CONFIG_PORT)] = wg_ep_port; + + if(strcmp(wg_ep_public_key, settings[FPSTR(FP_CONFIG_PUBLIC_KEY)].as().c_str()) != 0) changed = true; + settings[FPSTR(FP_CONFIG_PUBLIC_KEY)] = wg_ep_public_key; + + if(changed) configOutput(settings, TAG_WG); + return changed; +} + +bool wgSetConfig(const JsonObject& settings) +{ + Preferences preferences; + nvs_user_begin(preferences, "wg", false); + + configOutput(settings, TAG_WG); + bool changed = false; + bool changed_privkey = false; + + changed |= configSet((char *)wg_ip, sizeof(wg_ip), settings[FPSTR(FP_CONFIG_VPN_IP)], F("wgIp")); + if(!settings[FPSTR(FP_CONFIG_PRIVATE_KEY)].isNull() && + settings[FPSTR(FP_CONFIG_PRIVATE_KEY)].as() != String(FPSTR(D_PASSWORD_MASK))) { + changed |= strcmp(wg_private_key, settings[FPSTR(FP_CONFIG_PRIVATE_KEY)]) != 0; + strncpy(wg_private_key, settings[FPSTR(FP_CONFIG_PRIVATE_KEY)], sizeof(wg_private_key)-1); + wg_private_key[sizeof(wg_private_key)-1] = '\0'; + nvsUpdateString(preferences, FP_CONFIG_PRIVATE_KEY, settings[FPSTR(FP_CONFIG_PRIVATE_KEY)]); + } + changed |= changed_privkey; + changed |= configSet((char *)wg_ep_ip, sizeof(wg_ep_ip), settings[FPSTR(FP_CONFIG_HOST)], F("wgEpIp")); + changed |= configSet(wg_ep_port, settings[FPSTR(FP_CONFIG_PORT)], F("wgEpPort")); + changed |= configSet((char *)wg_ep_public_key, sizeof(wg_ep_public_key), settings[FPSTR(FP_CONFIG_PUBLIC_KEY)], F("wgEpPubKey")); + + if (changed && network_is_connected()) { + wg.end(); + wg_network_connected(); + } + + return changed; +} +#endif + + +#endif /* WIREGUARD */ diff --git a/src/sys/net/hasp_wireguard.h b/src/sys/net/hasp_wireguard.h new file mode 100644 index 000000000..486c711e8 --- /dev/null +++ b/src/sys/net/hasp_wireguard.h @@ -0,0 +1,40 @@ +/* MIT License - Copyright (c) 2023 Jaroslav Kysela + For full license information read the LICENSE file in the project folder */ + +#ifndef HASP_WIREGUARD_H +#define HASP_WIREGUARD_H + +void wg_setup(); +int wg_config_valid(); +void wg_network_disconnected(); +void wg_network_connected(); +void wg_get_statusupdate(char* buffer, size_t len); +int wg_get_ipaddress(char* buffer, size_t len); +void wg_get_info(JsonDocument& doc); + +#if HASP_USE_CONFIG > 0 +bool wgGetConfig(const JsonObject& settings); +bool wgSetConfig(const JsonObject& settings); +#endif + +#ifndef WIREGUARD_IP +#define WIREGUARD_IP "" +#endif + +#ifndef WIREGUARD_PRIVATE_KEY +#define WIREGUARD_PRIVATE_KEY "" +#endif + +#ifndef WIREGUARD_EP_IP +#define WIREGUARD_EP_IP "" +#endif + +#ifndef WIREGUARD_EP_PORT +#define WIREGUARD_EP_PORT 51820 +#endif + +#ifndef WIREGUARD_EP_PUBLIC_KEY +#define WIREGUARD_EP_PUBLIC_KEY "" +#endif + +#endif diff --git a/src/sys/svc/hasp_http.cpp b/src/sys/svc/hasp_http.cpp index d9b121589..6139b177c 100644 --- a/src/sys/svc/hasp_http.cpp +++ b/src/sys/svc/hasp_http.cpp @@ -408,6 +408,10 @@ bool http_save_config() #if HASP_USE_WIFI > 0 } else if(save == FP_WIFI) { updated = wifiSetConfig(settings.as()); +#endif +#if HASP_USE_WIREGUARD > 0 + } else if(save == FP_WG) { + updated = wgSetConfig(settings.as()); #endif } } @@ -635,6 +639,10 @@ static void webHandleApi() add_license(obj, "AceButton", "2018", "Brian T. Park", "mit"); obj = doc.createNestedObject(); add_license(obj, "QR Code generator", "", "Project Nayuki", "mit"); +#if HASP_USE_WIREGUARD > 0 + obj = doc.createNestedObject(); + add_license(obj, "WireGuard", "2021", "Kenta Ida fugafuga.org, Daniel Hope www.floorsense.nz", "bsd", 1); +#endif } { char output[HTTP_PAGE_SIZE]; @@ -688,6 +696,11 @@ static void webHandleApi() settings.createNestedObject(module); timeGetConfig(settings[module]); #endif +#if HASP_USE_WIREGUARD > 0 + module = FPSTR(FP_WG); + settings.createNestedObject(module); + wgGetConfig(settings[module]); +#endif #if HASP_USE_MQTT > 0 module = FPSTR(FP_MQTT); settings.createNestedObject(module); @@ -790,6 +803,11 @@ static void webHandleApiConfig() timeSetConfig(settings); } else #endif +#if HASP_USE_WIREGUARD > 0 + if(!strcasecmp(endpoint_key, FP_WG)) { + wgSetConfig(settings); + } else +#endif #if HASP_USE_MQTT > 0 if(!strcasecmp(endpoint_key, FP_MQTT)) { mqttSetConfig(settings); @@ -831,6 +849,11 @@ static void webHandleApiConfig() timeGetConfig(settings); } else #endif +#if HASP_USE_WIREGUARD > 0 + if(!strcasecmp(endpoint_key, FP_WG)) { + wgGetConfig(settings); + } else +#endif #if HASP_USE_MQTT > 0 if(!strcasecmp(endpoint_key, FP_MQTT)) { mqttGetConfig(settings); @@ -937,6 +960,8 @@ static void http_handle_info() {{ item }} Wifi {{ item }} +WireGuard +{{ item }} Module {{ item }} )"; @@ -1415,6 +1440,9 @@ static void http_handle_config() #if HASP_USE_WIFI > 0 html[min(i++, len)] = R"()"; #endif +#if HASP_USE_WIREGUARD > 0 + html[min(i++, len)] = R"()"; +#endif #if HASP_USE_MQTT > 0 html[min(i++, len)] = R"()"; #endif @@ -2302,6 +2330,50 @@ static void http_handle_wifi() #endif // HASP_USE_WIFI +//////////////////////////////////////////////////////////////////////////////////////////////////// +#if HASP_USE_WIREGUARD > 0 +static void http_handle_wireguard() +{ // http://plate01/config/wireguard + if(!http_is_authenticated(F("config/wireguard"))) return; + + const char* html[20]; + int i = 0; + int len = (sizeof(html) / sizeof(html[0])) - 1; + + html[min(i++, len)] = "

"; + html[min(i++, len)] = haspDevice.get_hostname(); + html[min(i++, len)] = "


"; + html[min(i++, len)] = R"( +

+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
)"; + html[min(i++, len)] = R"(
)"; + html[min(i++, len)] = R"()"; + http_send_content(html, min(i, len)); +} + +#endif // HASP_USE_WIREGUARD + static inline int handleFirmwareFile(String path) { String contentType((char*)0); @@ -2715,6 +2787,9 @@ void httpSetup() #if HASP_USE_WIFI > 0 webServer.on("/config/wifi", http_handle_wifi); #endif +#if HASP_USE_WIREGUARD > 0 + webServer.on("/config/wireguard", http_handle_wireguard); +#endif #if HASP_USE_GPIO > 0 webServer.on("/config/gpio", webHandleGpioConfig); webServer.on("/config/gpio/options", webHandleGpioOutput); diff --git a/src/sys/svc/hasp_http_async.cpp b/src/sys/svc/hasp_http_async.cpp index 9232cf0d7..d73f112f9 100644 --- a/src/sys/svc/hasp_http_async.cpp +++ b/src/sys/svc/hasp_http_async.cpp @@ -1259,7 +1259,7 @@ void webHandleMqttConfig(AsyncWebServerRequest* request) //////////////////////////////////////////////////////////////////////////////////////////////////// void webHandleGuiConfig(AsyncWebServerRequest* request) -{ // http://plate01/config/wifi +{ // http://plate01/config/gui if(!httpIsAuthenticated(request, F("config/gui"))) return; {