Public Access
VPN: a WireGuard tunnel (#8)
The device joins a WireGuard network over whatever Wi-Fi it is on: one peer, IPv4. A client's .conf is imported from the card (/vpn/wg0.conf) and kept in the device's settings, private key included, never shown; Settings offers to delete the file. A switch brings the tunnel up until the next restart, "Start with Wi-Fi" every time; it waits for the clock, which a handshake needs. VPN shows in the Status Bar. The protocol is esphome/wireguard 0.4.8. It calls lwIP without lwIP's lock, which this framework checks: every call into it is made with the lock held. What goes through the tunnel is everything (AllowedIPs 0.0.0.0/0) or the one subnet the device's tunnel address is in: lwIP routes by an interface's subnet or by default, nothing finer. The import says how many ranges it can't reach. Checked against a test peer in both directions and against a real server, with a configuration uploaded from a phone (docs/milestones/N1.md). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EhqxQ49eCju4CzKYNjZzwT
This commit is contained in:
@@ -35,6 +35,9 @@ bool SettingsApp::onKey(const KeyEvent& e) {
|
||||
case Page::Firmware:
|
||||
if (!firmwarePage_.onKey(e)) page_ = Page::Menu;
|
||||
return true;
|
||||
case Page::Vpn:
|
||||
if (!vpnPage_.onKey(e)) page_ = Page::Menu;
|
||||
return true;
|
||||
case Page::Debug:
|
||||
if (!debugPage_.onKey(e)) page_ = Page::Menu;
|
||||
return true;
|
||||
@@ -79,6 +82,10 @@ bool SettingsApp::onMenuKey(const KeyEvent& e) {
|
||||
page_ = Page::Firmware;
|
||||
firmwarePage_.enter();
|
||||
break;
|
||||
case Row::Vpn:
|
||||
page_ = Page::Vpn;
|
||||
vpnPage_.enter();
|
||||
break;
|
||||
case Row::DebugConsole:
|
||||
page_ = Page::Debug;
|
||||
debugPage_.enter();
|
||||
@@ -139,6 +146,7 @@ void SettingsApp::help(std::vector<KeyHelp>& out) const {
|
||||
case Page::Wifi: wifiPage_.help(out); break;
|
||||
case Page::Firmware: firmwarePage_.help(out); break;
|
||||
case Page::Debug: debugPage_.help(out); break;
|
||||
case Page::Vpn: vpnPage_.help(out); break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -147,6 +155,7 @@ const char* SettingsApp::helpTitle() const {
|
||||
case Page::Wifi: return wifiPage_.helpTitle();
|
||||
case Page::Firmware: return firmwarePage_.helpTitle();
|
||||
case Page::Debug: return debugPage_.helpTitle();
|
||||
case Page::Vpn: return "VPN";
|
||||
case Page::About: return "About";
|
||||
default: return nullptr;
|
||||
}
|
||||
@@ -154,7 +163,7 @@ const char* SettingsApp::helpTitle() const {
|
||||
|
||||
void SettingsApp::update(uint32_t nowMs) {
|
||||
// Live values on About and Firmware.
|
||||
bool live = page_ == Page::About || page_ == Page::Firmware || page_ == Page::Debug ||
|
||||
bool live = page_ == Page::About || page_ == Page::Firmware || page_ == Page::Debug || page_ == Page::Vpn ||
|
||||
(page_ == Page::Wifi && wifiPage_.live());
|
||||
if (live && nowMs - lastRefreshMs_ >= 500) {
|
||||
lastRefreshMs_ = nowMs;
|
||||
@@ -213,6 +222,7 @@ void SettingsApp::draw(Canvas& c) {
|
||||
case Page::Wifi: wifiPage_.draw(c); break;
|
||||
case Page::Firmware: firmwarePage_.draw(c); break;
|
||||
case Page::Debug: debugPage_.draw(c); break;
|
||||
case Page::Vpn: vpnPage_.draw(c); break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
#include "services/clock_service.h"
|
||||
#include "services/storage_service.h"
|
||||
#include "apps/debug_console_page.h"
|
||||
#include "apps/vpn_page.h"
|
||||
#include "apps/firmware_page.h"
|
||||
#include "apps/wifi_settings_page.h"
|
||||
#include "settings_menu.h"
|
||||
@@ -31,6 +32,7 @@ struct SettingsAppDeps {
|
||||
WifiService& wifi;
|
||||
SavedNetworks& savedNetworks;
|
||||
UpdateService& update;
|
||||
VpnService& vpn;
|
||||
};
|
||||
|
||||
// Settings: every user-facing setting, plus the Wi-Fi, Firmware, Debug Console and About pages.
|
||||
@@ -41,7 +43,8 @@ class SettingsApp : public App {
|
||||
menu_(deps.settings),
|
||||
wifiPage_(deps.settings, deps.savedNetworks, deps.wifi, deps.bus),
|
||||
firmwarePage_(deps.update, deps.wifi, deps.storage),
|
||||
debugPage_(deps.settings, deps.wifi) {}
|
||||
debugPage_(deps.settings, deps.wifi),
|
||||
vpnPage_(deps.settings, deps.vpn, deps.storage, deps.clock) {}
|
||||
void onEnter() override;
|
||||
bool onKey(const KeyEvent& e) override;
|
||||
void update(uint32_t nowMs) override;
|
||||
@@ -55,7 +58,7 @@ class SettingsApp : public App {
|
||||
bool showsSecret() const override { return page_ == Page::Debug; } // the Debug Console's token
|
||||
|
||||
private:
|
||||
enum class Page { Menu, Text, Choice, About, Wifi, Firmware, Debug };
|
||||
enum class Page { Menu, Text, Choice, About, Wifi, Firmware, Debug, Vpn };
|
||||
|
||||
bool onMenuKey(const KeyEvent& e);
|
||||
bool onTextKey(const KeyEvent& e);
|
||||
@@ -69,6 +72,7 @@ class SettingsApp : public App {
|
||||
WifiSettingsPage wifiPage_;
|
||||
FirmwarePage firmwarePage_;
|
||||
DebugConsolePage debugPage_;
|
||||
VpnPage vpnPage_;
|
||||
Page page_ = Page::Menu;
|
||||
ListModel list_{theme::kContent.h / theme::kLineHeight};
|
||||
ListModel choices_{theme::kContent.h / theme::kLineHeight};
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
#include "apps/vpn_page.h"
|
||||
|
||||
#include <SD.h>
|
||||
|
||||
#include "app_keys.h"
|
||||
#include "ipv4.h"
|
||||
#include "ui/fonts.h"
|
||||
#include "ui/theme.h"
|
||||
#include "ui/widgets.h"
|
||||
|
||||
namespace roro {
|
||||
|
||||
void VpnPage::enter() {
|
||||
list_.setCount(kRows);
|
||||
confirm_.reset();
|
||||
message_.clear();
|
||||
}
|
||||
|
||||
bool VpnPage::onKey(const KeyEvent& e) {
|
||||
if (confirm_) {
|
||||
confirm_->onKey(e);
|
||||
int result = confirm_->result();
|
||||
if (result == DialogModel::kPending) return true;
|
||||
Ask asked = ask_;
|
||||
ask_ = Ask::None;
|
||||
confirm_.reset();
|
||||
if (result == 1 && asked == Ask::DeleteFile) {
|
||||
storage_.runJob([]() { SD.remove(kConfPath); });
|
||||
message_ = "Imported, and the file is deleted";
|
||||
} else if (result == 1 && asked == Ask::Forget) {
|
||||
vpn_.forget();
|
||||
message_ = "Forgotten";
|
||||
}
|
||||
return true;
|
||||
}
|
||||
switch (e.key) {
|
||||
case Key::Up: list_.up(); break;
|
||||
case Key::Down: list_.down(); break;
|
||||
case Key::Back: return false;
|
||||
case Key::Left:
|
||||
case Key::Right:
|
||||
case Key::Select:
|
||||
if (e.key != Key::Select && list_.selected() > kAuto) break;
|
||||
message_.clear();
|
||||
switch (list_.selected()) {
|
||||
case kSwitch:
|
||||
if (!vpn_.configured()) message_ = "Import a .conf first";
|
||||
else vpn_.want(!vpn_.wanted());
|
||||
break;
|
||||
case kAuto:
|
||||
if (!vpn_.configured()) message_ = "Import a .conf first";
|
||||
else settings_.setBool(Setting::VpnAuto, !settings_.getBool(Setting::VpnAuto));
|
||||
break;
|
||||
case kImport: {
|
||||
std::string why = vpn_.importFile(storage_, kConfPath);
|
||||
if (!why.empty()) {
|
||||
message_ = why;
|
||||
break;
|
||||
}
|
||||
message_ = "Imported";
|
||||
ask_ = Ask::DeleteFile; // the card can be taken out, and the key is in that file
|
||||
confirm_.reset(new DialogModel({"Keep it", "Delete it"}));
|
||||
break;
|
||||
}
|
||||
case kForget:
|
||||
if (!vpn_.configured()) break;
|
||||
ask_ = Ask::Forget;
|
||||
confirm_.reset(new DialogModel({"Cancel", "Forget"}));
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void VpnPage::help(std::vector<KeyHelp>& out) const {
|
||||
if (confirm_) return keys::add(out, keys::kDialog);
|
||||
keys::add(out, keys::kVpn);
|
||||
}
|
||||
|
||||
void VpnPage::draw(Canvas& c) {
|
||||
const auto& area = theme::kContent;
|
||||
c.setTextDatum(top_left);
|
||||
bool set = vpn_.configured();
|
||||
widgets::list(
|
||||
c, list_, {area.x, area.y, area.w, kRows * theme::kLineHeight},
|
||||
[](int i) -> std::string {
|
||||
switch (i) {
|
||||
case kSwitch: return "VPN";
|
||||
case kAuto: return "Start with Wi-Fi";
|
||||
case kImport: return "Import /vpn/wg0.conf";
|
||||
default: return "Forget it";
|
||||
}
|
||||
},
|
||||
[&](int i) -> std::string {
|
||||
switch (i) {
|
||||
case kSwitch: return !set ? "Not set" : vpn_.wanted() ? "On" : "Off";
|
||||
case kAuto: return settings_.getBool(Setting::VpnAuto) ? "On" : "Off";
|
||||
default: return "";
|
||||
}
|
||||
});
|
||||
|
||||
int y = area.y + kRows * theme::kLineHeight + 4;
|
||||
c.setFont(&fonts::small);
|
||||
auto line = [&](const std::string& text, uint16_t colour) {
|
||||
c.setTextColor(colour);
|
||||
c.drawString(text.c_str(), 4, y);
|
||||
y += 10;
|
||||
};
|
||||
if (set) {
|
||||
const net::WgConfig& k = vpn_.config();
|
||||
std::string state = std::string("It is ") + vpn_.stateText();
|
||||
int64_t now = clock_.utcNow(), last = vpn_.lastHandshake();
|
||||
if (vpn_.state() == VpnService::State::Up && now >= 0 && last > 0 && now >= last) state += ", heard " + std::to_string(now - last) + " s ago";
|
||||
line(state, vpn_.state() == VpnService::State::Up ? theme::kAccent : theme::kText);
|
||||
line("Server " + k.endpointHost + ":" + std::to_string(k.endpointPort), theme::kMuted);
|
||||
line("This device " + net::formatIpv4(k.address) + ", through it " + net::describeWgRouting(k), theme::kMuted);
|
||||
} else {
|
||||
line("Copy a WireGuard .conf to the card as", theme::kMuted);
|
||||
line(std::string(kConfPath) + ", then import it.", theme::kMuted);
|
||||
}
|
||||
if (!message_.empty()) line(message_, theme::kWarning);
|
||||
else if (!vpn_.lastError().empty()) line(vpn_.lastError(), theme::kWarning);
|
||||
|
||||
if (confirm_ && ask_ == Ask::DeleteFile)
|
||||
widgets::dialog(c, "Delete the file?", "It is stored in the device now. The file on the card still holds the private key.", *confirm_);
|
||||
else if (confirm_)
|
||||
widgets::dialog(c, "Forget the VPN?", "The tunnel stops and its keys are erased from the device.", *confirm_);
|
||||
}
|
||||
|
||||
} // namespace roro
|
||||
@@ -0,0 +1,47 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "dialog_model.h"
|
||||
#include "key_event.h"
|
||||
#include "key_help.h"
|
||||
#include "list_model.h"
|
||||
#include "services/clock_service.h"
|
||||
#include "services/storage_service.h"
|
||||
#include "services/vpn_service.h"
|
||||
#include "settings.h"
|
||||
#include "ui/canvas.h"
|
||||
|
||||
namespace roro {
|
||||
|
||||
// Settings > VPN (issue #8): the switch, "Start with Wi-Fi", importing a `.conf` from the card
|
||||
// and forgetting it, and what the tunnel is doing. No key is ever on this page.
|
||||
class VpnPage {
|
||||
public:
|
||||
static constexpr const char* kConfPath = "/vpn/wg0.conf";
|
||||
|
||||
VpnPage(Settings& settings, VpnService& vpn, StorageService& storage, ClockService& clock)
|
||||
: settings_(settings), vpn_(vpn), storage_(storage), clock_(clock) {}
|
||||
|
||||
void enter();
|
||||
bool onKey(const KeyEvent& e); // false: leave the page
|
||||
void draw(Canvas& c);
|
||||
void help(std::vector<KeyHelp>& out) const;
|
||||
|
||||
private:
|
||||
enum Row { kSwitch, kAuto, kImport, kForget, kRows };
|
||||
enum class Ask { None, DeleteFile, Forget };
|
||||
|
||||
Settings& settings_;
|
||||
VpnService& vpn_;
|
||||
StorageService& storage_;
|
||||
ClockService& clock_;
|
||||
ListModel list_{kRows};
|
||||
std::unique_ptr<DialogModel> confirm_;
|
||||
Ask ask_ = Ask::None;
|
||||
std::string message_;
|
||||
};
|
||||
|
||||
} // namespace roro
|
||||
+49
-2
@@ -12,6 +12,7 @@
|
||||
#include "apps/demo_app.h"
|
||||
#include "apps/note_editor.h"
|
||||
#include "apps/shell_app.h"
|
||||
#include "services/vpn_service.h"
|
||||
#include "services/web_share.h"
|
||||
#include "apps/gemini_app.h"
|
||||
#include "apps/gnss_app.h"
|
||||
@@ -27,6 +28,7 @@
|
||||
#include "event_bus.h"
|
||||
#include "file_receiver.h"
|
||||
#include "ipv4.h"
|
||||
#include "wg_config.h"
|
||||
#include "traffic.h"
|
||||
#include "key_mapper.h"
|
||||
#include "platform/console.h"
|
||||
@@ -86,6 +88,7 @@ static WifiService* wifi;
|
||||
static IrcService* irc;
|
||||
static UpdateService* update;
|
||||
static DebugConsole* debugConsole;
|
||||
static VpnService* vpnService; // not in Safe Mode
|
||||
static Notifier* notifier;
|
||||
static LauncherApp launcher;
|
||||
static AppManager* apps;
|
||||
@@ -132,6 +135,8 @@ static StatusInfo currentStatus() {
|
||||
s.radio = last && millis() - last < 400 ? StatusInfo::Radio::Packet : StatusInfo::Radio::Listening;
|
||||
}
|
||||
s.capturing = loraCapture && loraCapture->capturing();
|
||||
if (vpnService && vpnService->wanted())
|
||||
s.vpn = vpnService->state() == VpnService::State::Up ? StatusInfo::Vpn::Up : StatusInfo::Vpn::Trying;
|
||||
s.debug = !debugConsole->on() ? StatusInfo::Debug::Off : debugConsole->clientConnected() ? StatusInfo::Debug::Client : StatusInfo::Debug::On;
|
||||
using WifiState = WifiController::State;
|
||||
switch (wifi->state()) {
|
||||
@@ -209,6 +214,8 @@ void setup() {
|
||||
services.add(*update);
|
||||
debugConsole = new DebugConsole(*wifi, *storageService, settings);
|
||||
services.add(*debugConsole);
|
||||
vpnService = new VpnService(settings, *wifi, *clockService, bus);
|
||||
services.add(*vpnService);
|
||||
|
||||
apps = new AppManager(launcher);
|
||||
launcher.setManager(*apps);
|
||||
@@ -227,7 +234,7 @@ void setup() {
|
||||
apps->registerApp({"system", "System", false,
|
||||
new SystemApp(*wifi, *battery, *storageService, *radioService, *gnssService, nvs)});
|
||||
apps->registerApp({"settings", "Settings", false,
|
||||
new SettingsApp({settings, bus, *apps, *battery, *storageService, *clockService, *wifi, *savedNetworks, *update})});
|
||||
new SettingsApp({settings, bus, *apps, *battery, *storageService, *clockService, *wifi, *savedNetworks, *update, *vpnService})});
|
||||
apps->registerApp({"demo", "Widget demo", true, new DemoApp(bus)});
|
||||
apps->registerApp({"setup", "Setup", true, new SetupApp(settings, *apps)});
|
||||
|
||||
@@ -667,6 +674,7 @@ static const char* const kHelp =
|
||||
"update check | update list | update status | update install <tag> the project's releases on Gitea\n"
|
||||
"sd card | sd list | cat <path> | log <text> | burst | sound on|off | short | normal\n"
|
||||
"Irc | Wifi | Gnss | Gemini | Lora | Storage | Notes | Shell | System | Settings open that App: a capital letter is an App, not a command\n"
|
||||
"vpn status | vpn up [seconds] | vpn down | vpn import [path] | vpn forget | vpn auto on|off the WireGuard tunnel (Settings > VPN); import reads /vpn/wg0.conf; with seconds, it goes down by itself\n"
|
||||
"debug status | debug off [seconds] the Debug Console over Wi-Fi (Settings > Debug Console); with seconds, it comes back\n"
|
||||
"debug on | debug token <16 to 64 characters> | debug token new (USB serial only) switch it on, set its token\n"
|
||||
"crash abort|wdt crash on purpose (to test crash reports and Safe Mode)\n"
|
||||
@@ -726,6 +734,44 @@ static void saveScreenshot() {
|
||||
});
|
||||
}
|
||||
|
||||
// `vpn ...` (issue #8). Nothing here prints a key.
|
||||
static void vpnCommand(const String& arg) {
|
||||
if (!vpnService) return (void)console.println("vpn: not available in Safe Mode");
|
||||
VpnService& v = *vpnService;
|
||||
if (arg == "up" || arg.startsWith("up ")) {
|
||||
if (!v.configured()) return (void)console.println("vpn: error not set: copy a .conf to /vpn/wg0.conf, then `vpn import`");
|
||||
uint32_t seconds = arg.length() > 3 ? constrain(arg.substring(3).toInt(), 0, 86400) : 0;
|
||||
v.want(true, seconds);
|
||||
if (seconds) console.printf("vpn: on for %lu s\n", (unsigned long)seconds);
|
||||
else console.println("vpn: on");
|
||||
} else if (arg == "down") {
|
||||
v.want(false);
|
||||
console.println("vpn: off");
|
||||
} else if (arg == "import" || arg.startsWith("import ")) {
|
||||
std::string path = arg.length() > 7 ? arg.substring(7).c_str() : "/vpn/wg0.conf";
|
||||
std::string why = v.importFile(*storageService, path);
|
||||
if (!why.empty()) return (void)console.printf("vpn: error %s\n", why.c_str());
|
||||
console.printf("vpn: imported, through it %s. %s still holds the private key: `rm -f` it\n", net::describeWgRouting(v.config()).c_str(), path.c_str());
|
||||
} else if (arg == "forget") {
|
||||
v.forget();
|
||||
console.println("vpn: forgotten");
|
||||
} else if (arg == "status") {
|
||||
if (!v.configured()) return (void)console.println("vpn: not set");
|
||||
const net::WgConfig& k = v.config();
|
||||
console.printf("vpn: %s%s, server %s:%u, this device %s/%d, through it %s\n", v.wanted() ? "" : "off, ", v.wanted() ? v.stateText() : "configured",
|
||||
k.endpointHost.c_str(), (unsigned)k.endpointPort, net::formatIpv4(k.address).c_str(), k.prefix, net::describeWgRouting(k).c_str());
|
||||
int64_t now = clockService->utcNow(), last = v.lastHandshake();
|
||||
if (last > 0 && now >= last) console.printf("vpn: last handshake %ld s ago\n", (long)(now - last));
|
||||
if (!v.lastError().empty()) console.printf("vpn: %s\n", v.lastError().c_str());
|
||||
console.printf("vpn: start with Wi-Fi %s\n", settings.getBool(Setting::VpnAuto) ? "on" : "off");
|
||||
} else if (arg == "auto on" || arg == "auto off") {
|
||||
settings.setBool(Setting::VpnAuto, arg == "auto on");
|
||||
console.printf("vpn: start with Wi-Fi %s\n", arg == "auto on" ? "on" : "off");
|
||||
} else {
|
||||
console.println("vpn: status | up [seconds] | down | import [path] | forget | auto on|off");
|
||||
}
|
||||
}
|
||||
|
||||
// Fn+p (issue #83): the screen as it is, dialog, help panel or Toast included. Not the page that
|
||||
// shows the Debug Console's token: a picture of it is a copy of the token in a file.
|
||||
static void screenshotKey() {
|
||||
@@ -820,6 +866,7 @@ static void runCommand(String line, bool fromSerial = false) {
|
||||
else console.println("Not now: Setup is running");
|
||||
return;
|
||||
}
|
||||
if (line == "vpn" || line.startsWith("vpn ")) return vpnCommand(line.length() > 4 ? line.substring(4) : String("status"));
|
||||
if (line.startsWith("debug ")) return debugCommand(line.substring(6), fromSerial);
|
||||
if (line == "screenshot" || line.startsWith("screenshot ")) {
|
||||
uint32_t seconds = constrain(line.substring(10).toInt(), 0, 60);
|
||||
@@ -1157,7 +1204,7 @@ static void runCommand(String line, bool fromSerial = false) {
|
||||
console.printf("wifi: address %s/%d (%s), gateway %s\n", c.address.c_str(), c.prefix, c.fixed ? "fixed" : "DHCP",
|
||||
c.gateway.empty() ? "none" : c.gateway.c_str());
|
||||
console.printf("wifi: dns %s %s (%s)\n", c.dns[0].empty() ? "none" : c.dns[0].c_str(), c.dns[1].c_str(),
|
||||
c.dnsFromSettings ? "Settings" : "DHCP");
|
||||
vpnService && vpnService->dnsThroughIt() ? "VPN" : c.dnsFromSettings ? "Settings" : "DHCP");
|
||||
console.print("wifi: ntp");
|
||||
for (int i = 0; i < c.ntpCount; i++) console.printf(" %s (%s%s)", c.ntp[i].server.c_str(), c.ntp[i].fromDhcp ? "DHCP" : "Settings", c.ntp[i].answered ? ", answered" : "");
|
||||
console.println(c.ntpCount ? "" : " none");
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
#include "services/vpn_service.h"
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <SD.h>
|
||||
|
||||
#include <esp_wireguard.h>
|
||||
#include <lwip/dns.h>
|
||||
#include <lwip/tcpip.h>
|
||||
|
||||
#include "ipv4.h"
|
||||
#include "platform/console.h"
|
||||
|
||||
namespace roro {
|
||||
|
||||
namespace {
|
||||
constexpr uint32_t kRetryMs = 10000;
|
||||
constexpr size_t kMaxConf = 4096;
|
||||
|
||||
// The library calls lwIP's raw functions and takes no lock; this build checks that the lock is
|
||||
// held (CONFIG_LWIP_CHECK_THREAD_SAFETY) and stops the device when it isn't.
|
||||
struct LwipLock {
|
||||
LwipLock() { LOCK_TCPIP_CORE(); }
|
||||
~LwipLock() { UNLOCK_TCPIP_CORE(); }
|
||||
};
|
||||
} // namespace
|
||||
|
||||
struct VpnService::Tunnel {
|
||||
wireguard_config_t config = ESP_WIREGUARD_CONFIG_DEFAULT();
|
||||
wireguard_ctx_t ctx = ESP_WIREGUARD_CONTEXT_DEFAULT();
|
||||
std::string address, netmask; // what `config` points into, with config_'s own strings
|
||||
bool inited = false, connected = false, isDefault = false, dnsIn = false;
|
||||
ip_addr_t dnsBefore[2];
|
||||
};
|
||||
|
||||
const char* VpnService::stateText() const {
|
||||
switch (state_) {
|
||||
case State::NoConfig: return "not set";
|
||||
case State::Off: return "off";
|
||||
case State::WaitingWifi: return "waiting for Wi-Fi";
|
||||
case State::WaitingClock: return "waiting for the clock";
|
||||
case State::Resolving: return "looking up the server";
|
||||
case State::Trying: return "no answer yet";
|
||||
case State::Up: return "up";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
void VpnService::loadConfig() {
|
||||
const std::string& stored = settings_.getString(Setting::VpnConfig);
|
||||
configured_ = !stored.empty() && net::parseWgConf(stored, config_).empty();
|
||||
if (!configured_) config_ = net::WgConfig();
|
||||
}
|
||||
|
||||
void VpnService::start() {
|
||||
loadConfig();
|
||||
wanted_ = configured_ && settings_.getBool(Setting::VpnAuto);
|
||||
state_ = !configured_ ? State::NoConfig : State::Off;
|
||||
}
|
||||
|
||||
void VpnService::want(bool on, uint32_t seconds) {
|
||||
wanted_ = on && configured_;
|
||||
timed_ = wanted_ && seconds > 0;
|
||||
untilMs_ = millis() + seconds * 1000;
|
||||
retryMs_ = 0;
|
||||
if (!wanted_) takeDown();
|
||||
}
|
||||
|
||||
std::string VpnService::import(const std::string& confText) {
|
||||
net::WgConfig fresh;
|
||||
std::string why = net::parseWgConf(confText, fresh);
|
||||
if (!why.empty()) return why;
|
||||
if (!settings_.setString(Setting::VpnConfig, net::toWgConf(fresh))) return "it couldn't be stored";
|
||||
takeDown(); // it comes back up by itself with the new one, if it was wanted
|
||||
loadConfig();
|
||||
state_ = State::Off;
|
||||
return "";
|
||||
}
|
||||
|
||||
std::string VpnService::importFile(StorageService& storage, const std::string& path) {
|
||||
std::string text, why;
|
||||
bool ran = storage.runAndWait([&]() {
|
||||
File f = SD.open(path.c_str(), FILE_READ);
|
||||
if (!f || f.isDirectory()) {
|
||||
why = "there is no " + path;
|
||||
return;
|
||||
}
|
||||
size_t size = f.size();
|
||||
if (size > kMaxConf) why = "that file is too big to be a .conf";
|
||||
else {
|
||||
text.resize(size);
|
||||
if (size && f.read(reinterpret_cast<uint8_t*>(&text[0]), size) != static_cast<int>(size)) why = "the card refused to read it";
|
||||
}
|
||||
f.close();
|
||||
});
|
||||
if (!ran) return "no SD card";
|
||||
if (!why.empty()) return why;
|
||||
return import(text);
|
||||
}
|
||||
|
||||
void VpnService::forget() {
|
||||
takeDown();
|
||||
wanted_ = false;
|
||||
settings_.setString(Setting::VpnConfig, "");
|
||||
settings_.setBool(Setting::VpnAuto, false);
|
||||
loadConfig();
|
||||
state_ = State::NoConfig;
|
||||
}
|
||||
|
||||
void VpnService::bringUp() {
|
||||
if (!tunnel_) tunnel_ = new Tunnel();
|
||||
Tunnel& t = *tunnel_;
|
||||
net::WgRouting routing = net::routingOf(config_);
|
||||
t.address = net::formatIpv4(config_.address);
|
||||
t.netmask = net::formatIpv4(net::maskOf(routing.full ? config_.prefix : routing.prefix));
|
||||
t.config.private_key = config_.privateKey.c_str();
|
||||
t.config.public_key = config_.peerKey.c_str();
|
||||
t.config.preshared_key = config_.presharedKey.empty() ? nullptr : config_.presharedKey.c_str();
|
||||
t.config.address = t.address.c_str();
|
||||
t.config.netmask = t.netmask.c_str();
|
||||
t.config.endpoint = config_.endpointHost.c_str();
|
||||
t.config.port = config_.endpointPort;
|
||||
t.config.listen_port = config_.listenPort;
|
||||
t.config.persistent_keepalive = static_cast<uint16_t>(config_.keepalive);
|
||||
|
||||
LwipLock lock;
|
||||
esp_err_t err = ESP_OK;
|
||||
if (!t.inited) {
|
||||
err = esp_wireguard_init(&t.config, &t.ctx);
|
||||
t.inited = err == ESP_OK;
|
||||
}
|
||||
if (err == ESP_OK) err = esp_wireguard_connect(&t.ctx);
|
||||
if (err == ESP_ERR_RETRY) { // the server's name isn't resolved yet: asked again at the next tick
|
||||
state_ = State::Resolving;
|
||||
return;
|
||||
}
|
||||
if (err == ESP_OK) {
|
||||
// What may come out of the tunnel, and with "everything", where every packet now goes. The
|
||||
// tunnel's own packets don't: the library sends them on the interface it started on.
|
||||
for (int i = 0; i < config_.allowedCount && err == ESP_OK; i++) {
|
||||
std::string address = net::formatIpv4(config_.allowed[i].address), mask = net::formatIpv4(net::maskOf(config_.allowed[i].prefix));
|
||||
err = esp_wireguard_add_allowed_ip(&t.ctx, address.c_str(), mask.c_str());
|
||||
}
|
||||
}
|
||||
if (err != ESP_OK) {
|
||||
error_ = std::string("the tunnel couldn't start (") + esp_err_to_name(err) + ")";
|
||||
console.printf("vpn: error %s\n", error_.c_str());
|
||||
esp_wireguard_disconnect(&t.ctx);
|
||||
t = Tunnel();
|
||||
retryMs_ = millis() + kRetryMs;
|
||||
state_ = State::Trying;
|
||||
return;
|
||||
}
|
||||
if (routing.full) t.isDefault = esp_wireguard_set_default(&t.ctx) == ESP_OK;
|
||||
if (config_.mtu && t.ctx.netif) t.ctx.netif->mtu = static_cast<u16_t>(config_.mtu);
|
||||
// The file's DNS servers, if they can be reached through the tunnel at all.
|
||||
if (config_.dns[0] && net::wgReaches(config_, config_.dns[0])) {
|
||||
t.dnsIn = true;
|
||||
for (int i = 0; i < 2; i++) ip_addr_set_any(false, &t.dnsBefore[i]);
|
||||
keepDns();
|
||||
}
|
||||
t.connected = true;
|
||||
error_.clear();
|
||||
announced_ = false;
|
||||
lastHandshake_ = 0;
|
||||
state_ = State::Trying;
|
||||
console.printf("vpn: started, %s:%u, through it %s\n", config_.endpointHost.c_str(), (unsigned)config_.endpointPort, net::describeWgRouting(config_).c_str());
|
||||
}
|
||||
|
||||
bool VpnService::dnsThroughIt() const { return tunnel_ && tunnel_->dnsIn; }
|
||||
|
||||
// With lwIP's lock held. What is found in the two slots, if it isn't the tunnel's, is what goes
|
||||
// back when the tunnel stops: so a DHCP renewal while it is up is not lost.
|
||||
void VpnService::keepDns() {
|
||||
Tunnel& t = *tunnel_;
|
||||
for (int i = 0; i < 2; i++) {
|
||||
ip_addr_t wanted;
|
||||
ip_addr_set_zero_ip4(&wanted);
|
||||
if (config_.dns[i]) ip_addr_set_ip4_u32(&wanted, lwip_htonl(config_.dns[i]));
|
||||
const ip_addr_t* now = dns_getserver(static_cast<u8_t>(i));
|
||||
if (ip_addr_cmp(now, &wanted)) continue;
|
||||
t.dnsBefore[i] = *now;
|
||||
dns_setserver(static_cast<u8_t>(i), &wanted);
|
||||
}
|
||||
}
|
||||
|
||||
void VpnService::takeDown() {
|
||||
if (tunnel_) {
|
||||
Tunnel& t = *tunnel_;
|
||||
bool dns = t.dnsIn;
|
||||
{
|
||||
LwipLock lock;
|
||||
if (t.dnsIn)
|
||||
for (int i = 0; i < 2; i++) dns_setserver(static_cast<u8_t>(i), &t.dnsBefore[i]);
|
||||
if (t.isDefault) esp_wireguard_restore_default(&t.ctx);
|
||||
if (t.inited) esp_wireguard_disconnect(&t.ctx);
|
||||
}
|
||||
delete tunnel_;
|
||||
tunnel_ = nullptr;
|
||||
if (dns) wifi_.holdDns(false);
|
||||
console.println("vpn: stopped");
|
||||
}
|
||||
lastHandshake_ = 0;
|
||||
state_ = !configured_ ? State::NoConfig : State::Off;
|
||||
}
|
||||
|
||||
void VpnService::tick(uint32_t nowMs) {
|
||||
if (timed_ && static_cast<int32_t>(nowMs - untilMs_) >= 0) want(false);
|
||||
if (!configured_ || !wanted_) {
|
||||
if (tunnel_) takeDown();
|
||||
return;
|
||||
}
|
||||
// A tunnel doesn't outlive the network it was started on: the next one starts it afresh.
|
||||
if (wifi_.state() != WifiController::State::Connected) {
|
||||
if (tunnel_) takeDown();
|
||||
state_ = State::WaitingWifi;
|
||||
return;
|
||||
}
|
||||
if (clock_.utcNow() < 0) {
|
||||
state_ = State::WaitingClock;
|
||||
return;
|
||||
}
|
||||
if (!tunnel_ || !tunnel_->connected) {
|
||||
if (retryMs_ && static_cast<int32_t>(nowMs - retryMs_) < 0) return;
|
||||
retryMs_ = 0;
|
||||
bringUp();
|
||||
if (tunnel_ && tunnel_->dnsIn) wifi_.holdDns(true);
|
||||
return;
|
||||
}
|
||||
bool up;
|
||||
time_t last = 0;
|
||||
{
|
||||
LwipLock lock;
|
||||
up = esp_wireguard_peer_is_up(&tunnel_->ctx) == ESP_OK;
|
||||
esp_wireguard_latest_handshake(&tunnel_->ctx, &last);
|
||||
if (tunnel_->dnsIn) keepDns();
|
||||
}
|
||||
if (last > 0) lastHandshake_ = static_cast<int64_t>(last);
|
||||
State was = state_;
|
||||
state_ = up ? State::Up : State::Trying;
|
||||
if (state_ == State::Up && !announced_) {
|
||||
announced_ = true;
|
||||
bus_.publish(Event::withText(EventType::Notification, ("VPN up: " + config_.endpointHost).c_str(), static_cast<int32_t>(NotificationLevel::Info)));
|
||||
} else if (was == State::Up && state_ == State::Trying) {
|
||||
announced_ = false;
|
||||
bus_.publish(Event::withText(EventType::Notification, "VPN: the server stopped answering", static_cast<int32_t>(NotificationLevel::Warning)));
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace roro
|
||||
@@ -0,0 +1,74 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "event_bus.h"
|
||||
#include "service.h"
|
||||
#include "services/clock_service.h"
|
||||
#include "services/storage_service.h"
|
||||
#include "services/wifi_service.h"
|
||||
#include "settings.h"
|
||||
#include "wg_config.h"
|
||||
|
||||
namespace roro {
|
||||
|
||||
// The WireGuard tunnel (issue #8, docs/milestones/N1.md): one peer, IPv4, over whatever Wi-Fi the
|
||||
// device is on. The protocol is the `esphome/wireguard` library's; this decides when the tunnel
|
||||
// is up, takes lwIP's lock around every call into it (the library takes none), and puts the
|
||||
// tunnel's DNS servers in and out.
|
||||
//
|
||||
// It starts once Wi-Fi is connected and the clock is set: a handshake carries the time, and a
|
||||
// server refuses one older than the last it saw from this key.
|
||||
class VpnService : public Service {
|
||||
public:
|
||||
enum class State { NoConfig, Off, WaitingWifi, WaitingClock, Resolving, Trying, Up };
|
||||
|
||||
VpnService(Settings& settings, WifiService& wifi, ClockService& clock, EventBus& bus)
|
||||
: settings_(settings), wifi_(wifi), clock_(clock), bus_(bus) {}
|
||||
const char* name() const override { return "vpn"; }
|
||||
void start() override;
|
||||
void stop() override { takeDown(); }
|
||||
void tick(uint32_t nowMs) override;
|
||||
|
||||
State state() const { return state_; }
|
||||
const char* stateText() const;
|
||||
bool configured() const { return configured_; }
|
||||
const net::WgConfig& config() const { return config_; } // its keys are for the library only
|
||||
bool wanted() const { return wanted_; }
|
||||
// On or off, until the next restart; `seconds`: on for that long, then off by itself (for
|
||||
// trying a configuration from afar, when a wrong one would cut the connection it was sent over).
|
||||
void want(bool on, uint32_t seconds = 0);
|
||||
|
||||
// A `.conf`'s text, or the file itself. "" or why it wasn't taken. A tunnel that is up starts
|
||||
// again with the new one.
|
||||
std::string import(const std::string& confText);
|
||||
std::string importFile(StorageService& storage, const std::string& path);
|
||||
void forget();
|
||||
|
||||
bool dnsThroughIt() const; // the tunnel's DNS servers are the ones in use
|
||||
int64_t lastHandshake() const { return lastHandshake_; } // UTC seconds, 0: none yet
|
||||
const std::string& lastError() const { return error_; }
|
||||
|
||||
private:
|
||||
struct Tunnel; // the library's structures, kept out of this header
|
||||
|
||||
void bringUp();
|
||||
void takeDown();
|
||||
void loadConfig();
|
||||
void keepDns(); // puts the tunnel's servers back in if a DHCP renewal replaced them
|
||||
|
||||
Settings& settings_;
|
||||
WifiService& wifi_;
|
||||
ClockService& clock_;
|
||||
EventBus& bus_;
|
||||
net::WgConfig config_;
|
||||
bool configured_ = false, wanted_ = false, announced_ = false;
|
||||
State state_ = State::NoConfig;
|
||||
Tunnel* tunnel_ = nullptr;
|
||||
uint32_t untilMs_ = 0, retryMs_ = 0;
|
||||
bool timed_ = false;
|
||||
int64_t lastHandshake_ = 0;
|
||||
std::string error_;
|
||||
};
|
||||
|
||||
} // namespace roro
|
||||
@@ -52,6 +52,14 @@ void WifiService::ipSettingChanged(const std::string& ssid) {
|
||||
controller_.retryNow(millis());
|
||||
}
|
||||
|
||||
void WifiService::holdDns(bool held) {
|
||||
if (dnsHeld_ == held) return;
|
||||
dnsHeld_ = held;
|
||||
// Whoever held them puts back what it found (DHCP's servers can't be asked for again without
|
||||
// a new lease, which would drop every connection); ours are checked right away.
|
||||
if (!held) applyServers(Why::Check);
|
||||
}
|
||||
|
||||
// DNS and NTP as decided in Q108 and Q110. Run when connected, when a setting changes, and now
|
||||
// and then: a DHCP renewal puts DHCP's DNS back and clears the NTP slots it didn't fill.
|
||||
void WifiService::applyServers(Why why) {
|
||||
@@ -61,7 +69,9 @@ void WifiService::applyServers(Why why) {
|
||||
|
||||
bool wasFromSettings = dnsFromSettings_;
|
||||
dnsFromSettings_ = fixed_ || settings_.getBool(Setting::DnsAlways);
|
||||
if (dnsFromSettings_) {
|
||||
if (dnsHeld_) {
|
||||
// a tunnel's servers are in: see holdDns()
|
||||
} else if (dnsFromSettings_) {
|
||||
IPAddress dns1 = toIp(settings_.getString(Setting::Dns1)), dns2 = toIp(settings_.getString(Setting::Dns2));
|
||||
if (WiFi.dnsIP(0) != dns1 || WiFi.dnsIP(1) != dns2) WiFi.setDNS(dns1, dns2);
|
||||
} else if (why == Why::SettingsChanged && wasFromSettings) {
|
||||
|
||||
@@ -56,6 +56,8 @@ class WifiService : public Service {
|
||||
void ipSettingChanged(const std::string& ssid);
|
||||
// The DNS or NTP settings changed: use them now.
|
||||
void serversChanged() { applyServers(Why::SettingsChanged); }
|
||||
// While a tunnel has put its own DNS servers in (issue #8), ours are not put back over them.
|
||||
void holdDns(bool held);
|
||||
// The noise self-test switches the radio off for a few seconds. Not saved anywhere: a restart
|
||||
// during the test brings Wi-Fi back, which a changed setting wouldn't.
|
||||
void debugPause(bool paused) { paused_ = paused; }
|
||||
@@ -89,6 +91,7 @@ class WifiService : public Service {
|
||||
bool paused_ = false; // Debug Builds: off for a moment, whatever the setting says
|
||||
bool fixed_ = false; // the network in use has a Fixed address
|
||||
bool dnsFromSettings_ = false;
|
||||
bool dnsHeld_ = false;
|
||||
std::string ntpNames_[2]; // lwIP keeps the pointers, so the names live here
|
||||
uint32_t serversCheckedMs_ = 0;
|
||||
};
|
||||
|
||||
@@ -48,6 +48,11 @@ void statusBar(Canvas& c, const StatusInfo& info) {
|
||||
case StatusInfo::Wifi::Monitoring: right("MON", kAccent); break;
|
||||
case StatusInfo::Wifi::None: break;
|
||||
}
|
||||
switch (info.vpn) { // Q252: there while the tunnel is wanted, bright once the peer has answered
|
||||
case StatusInfo::Vpn::Trying: right("VPN", kMuted); break;
|
||||
case StatusInfo::Vpn::Up: right("VPN", kAccent); break;
|
||||
case StatusInfo::Vpn::Off: break;
|
||||
}
|
||||
switch (info.debug) { // Q190: there while the console listens, bright with someone connected
|
||||
case StatusInfo::Debug::On: right("DBG", kMuted); break;
|
||||
case StatusInfo::Debug::Client: right("DBG", kAccent); break;
|
||||
|
||||
+2
-1
@@ -31,12 +31,13 @@ struct StatusInfo {
|
||||
enum class Radio { None, Listening, Packet, Sweep } radio = Radio::None; // M3, Q101: Packet flashes
|
||||
bool capturing = false; // a LoRa Capture is recording (Q97)
|
||||
enum class Debug { Off, On, Client } debug = Debug::Off; // the Debug Console listens (ADR 0010, Q190)
|
||||
enum class Vpn { Off, Trying, Up } vpn = Vpn::Off; // the WireGuard tunnel (issue #8, Q252)
|
||||
|
||||
bool operator==(const StatusInfo& o) const {
|
||||
return title == o.title && batteryPercent == o.batteryPercent && clock == o.clock &&
|
||||
sdPresent == o.sdPresent && sdLevel == o.sdLevel && compose == o.compose && wifi == o.wifi &&
|
||||
wifiBars == o.wifiBars && unread == o.unread && gnss == o.gnss && gnssSatellites == o.gnssSatellites &&
|
||||
tracking == o.tracking && radio == o.radio && capturing == o.capturing && debug == o.debug;
|
||||
tracking == o.tracking && radio == o.radio && capturing == o.capturing && debug == o.debug && vpn == o.vpn;
|
||||
}
|
||||
bool operator!=(const StatusInfo& o) const { return !(*this == o); }
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user