From d644f0a516e3386e9e16a6f92537a5a5530f0814 Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko Date: Sun, 8 Nov 2026 23:37:54 +0200 Subject: [PATCH 1/6] GPS: optional anti-spoofing guard for position and time (GPS_GUARD) A spoofed GPS signal can move a fixed node anywhere and set its clock to any time; the clock only moves forward, so a time pushed into the future breaks timestamps and replay protection until fixed by hand. With GPS_GUARD, MicroNMEALocationProvider asks a GpsGuard before a fix is stored as the last fix (satellites, HDOP, optional region box, fence around the configured position, jump speed, N stable fixes) and before GPS time is written to the clock (trusted fix current, not before the build date, small steps once the clock is valid, drift-sized after the first sync). Without a trusted fix no live position is reported. CLI in CommonGpsPrefs: 'gps guard', 'gps guard accept', 'gps fence', 'gps ref'; CommonCLI keeps the reference on set lat/lon and gps setloc, resets the time anchor on manual clock sets and adds 'time force'. Ported from #3736 onto the GpsDriver/LocationProvider refactor. --- docs/cli_commands.md | 17 ++ src/helpers/CommonCLI.cpp | 15 + src/helpers/CommonCLI.h | 5 + src/helpers/CommonGpsPrefs.cpp | 63 ++++ src/helpers/CommonGpsPrefs.h | 5 + .../sensors/EnvironmentSensorManager.cpp | 10 + src/helpers/sensors/GpsGuard.h | 275 ++++++++++++++++++ src/helpers/sensors/LocationProvider.h | 7 + .../sensors/MicroNMEALocationProvider.h | 54 +++- src/helpers/sensors/RakLocationProvider.h | 17 ++ 10 files changed, 466 insertions(+), 2 deletions(-) create mode 100644 src/helpers/sensors/GpsGuard.h diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 44ff3a250..e21b6a8ea 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -69,6 +69,8 @@ This document provides an overview of CLI commands that can be sent to MeshCore **Parameters:** - `epoch_seconds`: Unix epoch time +**Note:** The clock only moves forward. To set it back (e.g. after the clock was pushed into the future by a wrong GPS time) use `time force `. + --- ### Send a flood advert @@ -1077,6 +1079,21 @@ region save --- +#### GPS anti-spoofing guard (When built with `GPS_GUARD`) +With `GPS_GUARD`, a fix becomes the node's last fix (position, telemetry, adverts) only after it passes plausibility checks: at least `GPS_GUARD_MIN_SATS` satellites, HDOP ≤ `GPS_GUARD_MAX_HDOP10`/10, inside the optional build-time region (`GPS_GUARD_LAT_MIN/MAX`, `GPS_GUARD_LON_MIN/MAX`), within the fence around the node's configured `lat`/`lon` (if set), no jump faster than `GPS_GUARD_MAX_SPEED_KMH`, and `GPS_GUARD_STABLE_FIXES` consistent fixes in a row. An unverified position is never reported. + +GPS time is written to the clock only while such a fix is current, never earlier than the firmware build date, and, once the clock is valid, only within `GPS_GUARD_TIME_MAX_STEP` seconds for the first sync and within clock drift (`GPS_GUARD_TIME_DRIFT_BASE` s + `GPS_GUARD_TIME_DRIFT_PPM`) afterwards. Setting the clock manually (`time`, `time force`, `clock sync`) resets that anchor. + +Covers serial NMEA receivers (`MicroNMEALocationProvider`). + +**Usage:** +- `gps guard`: status, e.g. `> ok 7sat time ok +1s`, `> rej region time rej nofix`, or `... ALERT gps-clk +3600s 75m` when a trusted fix has disagreed with the clock by the same offset for `GPS_GUARD_ALERT_MIN` minutes. While the alert is active, the offset in hours is also reported in telemetry on the next free channel. +- `gps guard accept`: while an alert is active, confirm that the GPS time is right and apply it to the clock. +- `gps fence`, `gps fence `: fence radius around the configured `lat`/`lon` (`0` = off). Default `GPS_GUARD_FENCE_M` (1000), not saved. +- `gps ref`: the reference position; follows `set lat`, `set lon` and `gps setloc`. + +--- + #### Set this node's location based on the GPS coordinates **Usage:** - `gps setloc` diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 978f9e062..fa3ad7897 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -211,6 +211,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re uint32_t curr = getRTCClock()->getCurrentTime(); if (sender_timestamp > curr) { getRTCClock()->setCurrentTime(sender_timestamp + 1); + CommonGpsPrefs::onClockSetManually(*_sensors); uint32_t now = getRTCClock()->getCurrentTime(); DateTime dt = DateTime(now); sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year()); @@ -225,11 +226,22 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re uint32_t now = getRTCClock()->getCurrentTime(); DateTime dt = DateTime(now); sprintf(reply, "%02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year()); + } else if (memcmp(command, "time force ", 11) == 0) { // set time, allowing it to go backwards + uint32_t secs = _atoi(&command[11]); + if (secs > 1700000000UL) { + getRTCClock()->setCurrentTime(secs); + CommonGpsPrefs::onClockSetManually(*_sensors); + DateTime dt = DateTime(getRTCClock()->getCurrentTime()); + sprintf(reply, "OK - clock forced: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year()); + } else { + strcpy(reply, "ERR: invalid epoch"); + } } else if (memcmp(command, "time ", 5) == 0) { // set time (to epoch seconds) uint32_t secs = _atoi(&command[5]); uint32_t curr = getRTCClock()->getCurrentTime(); if (secs > curr) { getRTCClock()->setCurrentTime(secs); + CommonGpsPrefs::onClockSetManually(*_sensors); uint32_t now = getRTCClock()->getCurrentTime(); DateTime dt = DateTime(now); sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year()); @@ -357,6 +369,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re } else if (memcmp(command, "gps setloc", 10) == 0) { _prefs->node_lat = _sensors->node_lat; _prefs->node_lon = _sensors->node_lon; + _prefs->getGpsPrefs()->applyGuardReference(*_sensors); savePrefs(); strcpy(reply, "OK"); } else if (memcmp(command, "gps advert", 10) == 0) { @@ -495,10 +508,12 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep strcpy(reply, _prefs->disable_fwd ? "OK - repeat is now OFF" : "OK - repeat is now ON"); } else if (memcmp(config, "lat ", 4) == 0) { _prefs->node_lat = atof(&config[4]); + _prefs->getGpsPrefs()->applyGuardReference(*_sensors); savePrefs(); strcpy(reply, "OK"); } else if (memcmp(config, "lon ", 4) == 0) { _prefs->node_lon = atof(&config[4]); + _prefs->getGpsPrefs()->applyGuardReference(*_sensors); savePrefs(); strcpy(reply, "OK"); } else if (memcmp(config, "flood.max.unscoped ", 19) == 0) { diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 33e27d2db..823f6c0fd 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -169,6 +169,11 @@ private: void setGpsEnabled(bool enabled) override { _parent->gps_enabled = enabled; markDirty(); } uint32_t getGpsPeriod() const override { return _parent->gps_period; } void setGpsPeriod(uint32_t seconds) override { _parent->gps_period = seconds; markDirty(); } + bool getGuardReference(double& lat, double& lon) const override { + lat = _parent->node_lat; + lon = _parent->node_lon; + return true; + } }; GPSPrefs gps; diff --git a/src/helpers/CommonGpsPrefs.cpp b/src/helpers/CommonGpsPrefs.cpp index f840f0a2c..8faf01a65 100644 --- a/src/helpers/CommonGpsPrefs.cpp +++ b/src/helpers/CommonGpsPrefs.cpp @@ -1,5 +1,8 @@ #include "CommonGpsPrefs.h" #include +#ifdef GPS_GUARD +#include +#endif bool CommonGpsPrefs::setGpsEnabled(SensorManager& sensors, bool enabled) { LocationProvider* location = sensors.getLocationProvider(); @@ -17,9 +20,28 @@ bool CommonGpsPrefs::setGpsPeriod(SensorManager& sensors, uint32_t seconds) { return true; } +void CommonGpsPrefs::applyGuardReference(SensorManager& sensors) const { +#ifdef GPS_GUARD + LocationProvider* location = sensors.getLocationProvider(); + GpsGuard* guard = location != nullptr ? location->getGuard() : nullptr; + double lat, lon; + if (guard != nullptr && getGuardReference(lat, lon)) guard->setReference(lat, lon); +#endif +} + +// The clock was set by hand: the guard drops its GPS time anchor and any alert. +void CommonGpsPrefs::onClockSetManually(SensorManager& sensors) { +#ifdef GPS_GUARD + LocationProvider* location = sensors.getLocationProvider(); + GpsGuard* guard = location != nullptr ? location->getGuard() : nullptr; + if (guard != nullptr) guard->clockSetManually(); +#endif +} + bool CommonGpsPrefs::apply(SensorManager& sensors) const { LocationProvider* location = sensors.getLocationProvider(); if (location == nullptr) return false; + applyGuardReference(sensors); location->setGpsPeriod(getGpsPeriod()); location->setGpsOn(isGpsEnabled()); return true; @@ -198,6 +220,47 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, } return true; } +#ifdef GPS_GUARD + if (memcmp(command, "gps guard", 9) == 0 || memcmp(command, "gps fence", 9) == 0 || + strcmp(command, "gps ref") == 0) { + LocationProvider* location = sensors.getLocationProvider(); + GpsGuard* guard = location != nullptr ? location->getGuard() : nullptr; + if (guard == nullptr) { + strcpy(reply, "Error, gps guard not supported"); + } else if (strcmp(command, "gps guard") == 0) { + reply[0] = '>'; reply[1] = ' '; + guard->formatStatus(reply + 2, 158); + } else if (strcmp(command, "gps guard accept") == 0) { + // operator confirms that the alerted GPS time is right: apply it to the clock + long offset; + if (!guard->isTimeAlert()) { + strcpy(reply, "Error, no time alert"); + } else if (!location->getClockOffset(offset) || + !guard->acceptAlertedTime(offset, (uint32_t)location->getTimestamp()) || + !location->applyTimeNow()) { + strcpy(reply, "Error, no current trusted fix with the alerted time"); + } else { + strcpy(reply, "OK - clock set from GPS"); + } + } else if (strcmp(command, "gps fence") == 0) { + sprintf(reply, "> %lu", (unsigned long)guard->getFence()); + } else if (memcmp(command, "gps fence ", 10) == 0) { + char* end; + unsigned long metres = strtoul(command + 10, &end, 10); + if (command[10] == '' || *end != '') { + strcpy(reply, "Error, invalid fence"); + } else { + guard->setFence((uint32_t)metres); + strcpy(reply, "OK"); + } + } else if (strcmp(command, "gps ref") == 0) { + snprintf(reply, 160, "> %.6f, %.6f", guard->getRefLat(), guard->getRefLon()); + } else { + return false; + } + return true; + } +#endif if (strcmp(command, "gps diag") == 0) { LocationProvider* location = sensors.getLocationProvider(); if (location == nullptr) { diff --git a/src/helpers/CommonGpsPrefs.h b/src/helpers/CommonGpsPrefs.h index 25cce1b11..7a7d57447 100644 --- a/src/helpers/CommonGpsPrefs.h +++ b/src/helpers/CommonGpsPrefs.h @@ -19,7 +19,12 @@ public: virtual uint32_t getGpsPeriod() const = 0; virtual void setGpsPeriod(uint32_t seconds) = 0; + // Reference position for the anti-spoofing guard (GPS_GUARD), e.g. the configured node position. + virtual bool getGuardReference(double& lat, double& lon) const { return false; } + bool setGpsEnabled(SensorManager& sensors, bool enabled); + void applyGuardReference(SensorManager& sensors) const; + static void onClockSetManually(SensorManager& sensors); bool setGpsPeriod(SensorManager& sensors, uint32_t seconds); bool apply(SensorManager& sensors) const; bool handleCommand(const char* command, SensorManager& sensors, char* reply); diff --git a/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index eafa11a3c..d8f2d1d86 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.cpp +++ b/src/helpers/sensors/EnvironmentSensorManager.cpp @@ -1,6 +1,9 @@ #include "EnvironmentSensorManager.h" #include +#if ENV_INCLUDE_GPS && defined(GPS_GUARD) +#include +#endif #if ENV_PIN_SDA && ENV_PIN_SCL #define TELEM_WIRE &Wire1 // Use Wire1 as the I2C bus for Environment Sensors @@ -641,6 +644,13 @@ bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, Cayen _active_sensors[i].query(next_available_channel, _active_sensors[i].sub_channel, telemetry); next_available_channel++; } + #if ENV_INCLUDE_GPS && defined(GPS_GUARD) + // GPS-vs-clock offset in hours on its own channel while the guard's time alert is active + GpsGuard* guard = _location->getGuard(); + if (guard != nullptr && guard->isTimeAlert()) { + telemetry.addAnalogInput(next_available_channel++, guard->getAlertOffset() / 3600.0f); + } + #endif } return true; diff --git a/src/helpers/sensors/GpsGuard.h b/src/helpers/sensors/GpsGuard.h new file mode 100644 index 000000000..238bc7e88 --- /dev/null +++ b/src/helpers/sensors/GpsGuard.h @@ -0,0 +1,275 @@ +#pragma once + +// GPS anti-spoofing guard (opt-in with GPS_GUARD). +// +// A location provider asks the guard before it stores a fix as its last fix and before it +// writes GPS time to the clock: +// - acceptFix(): plausibility checks (satellites, HDOP, optional build-time region, distance +// from a reference position, jump speed) and N consecutive consistent fixes; +// - acceptTime(): GPS time only while a trusted fix is current, not before this firmware +// was built, and once the clock is valid only small corrections (clock drift after the +// first accepted sync), so a spoofer cannot walk the clock away. +// A trusted fix that keeps disagreeing with the clock by the same offset raises an alert; +// the operator can then accept that GPS time (acceptAlertedTime()). + +#include +#include +#include +#include +#include +#include + +#ifndef GPS_GUARD_MIN_SATS + #define GPS_GUARD_MIN_SATS 4 +#endif +#ifndef GPS_GUARD_MAX_HDOP10 + #define GPS_GUARD_MAX_HDOP10 40 // HDOP 4.0 +#endif +#ifndef GPS_GUARD_FENCE_M + #define GPS_GUARD_FENCE_M 1000 // max distance from the reference position (0 = off) +#endif +#ifndef GPS_GUARD_STABLE_FIXES + #define GPS_GUARD_STABLE_FIXES 5 // consecutive consistent fixes (one per GPS second) +#endif +#ifndef GPS_GUARD_STABLE_M + #define GPS_GUARD_STABLE_M 100 +#endif +#ifndef GPS_GUARD_MAX_SPEED_KMH + #define GPS_GUARD_MAX_SPEED_KMH 250 // jump limit relative to the last trusted fix +#endif +#ifndef GPS_GUARD_TIME_MAX_STEP + #define GPS_GUARD_TIME_MAX_STEP 600 // max GPS-vs-clock correction (s) once the clock is valid +#endif +#ifndef GPS_GUARD_TIME_DRIFT_BASE + #define GPS_GUARD_TIME_DRIFT_BASE 5 // after the first sync: fixed allowance (s) ... +#endif +#ifndef GPS_GUARD_TIME_DRIFT_PPM + #define GPS_GUARD_TIME_DRIFT_PPM 100 // ... plus clock drift since that sync (~8.6 s/day) +#endif +#ifndef GPS_GUARD_ALERT_MIN + #define GPS_GUARD_ALERT_MIN 60 // alert after GPS disagrees with the clock this long ... +#endif +#ifndef GPS_GUARD_ALERT_TOLERANCE + #define GPS_GUARD_ALERT_TOLERANCE 60 // ... by an offset that stays within this many seconds +#endif +#ifndef GPS_GUARD_TRUSTED_MS + #define GPS_GUARD_TRUSTED_MS 5000 // a trusted fix is "current" for this long +#endif + +class GpsGuard { + double _ref_lat = 0, _ref_lon = 0; // 0,0 = no reference position + uint32_t _fence_m = GPS_GUARD_FENCE_M; + + bool _have_trusted = false; + unsigned long _last_trusted_ms = 0; + double _last_trusted_lat = 0, _last_trusted_lon = 0; + double _cand_lat = 0, _cand_lon = 0; + uint32_t _cand_time = 0; // GPS second of the last counted candidate + uint32_t _rej_log_time = 0; // GPS second of the last logged rejection + uint8_t _stable_count = 0; + char _fix_status[24] = "no fix"; + + char _time_status[24] = "-"; + bool _time_accepted = false; // a GPS time sync was accepted (drift budget anchor) + unsigned long _last_time_accept_ms = 0; + bool _time_disagree = false; + long _time_disagree_offset = 0; // GPS minus clock, seconds + unsigned long _time_disagree_since_ms = 0; + bool _time_alert = false; + + static double distanceM(double lat1, double lon1, double lat2, double lon2) { + const double R = 6371000.0, D2R = 0.017453292519943295; + double dlat = (lat2 - lat1) * D2R, dlon = (lon2 - lon1) * D2R; + double a = sin(dlat / 2) * sin(dlat / 2) + + cos(lat1 * D2R) * cos(lat2 * D2R) * sin(dlon / 2) * sin(dlon / 2); + return 2 * R * atan2(sqrt(a), sqrt(1 - a)); + } + + bool trustedFixIsCurrent() const { + return _have_trusted && (uint32_t)(millis() - _last_trusted_ms) <= GPS_GUARD_TRUSTED_MS; + } + + void trackTimeDisagreement(long offset) { + const unsigned long now = millis(); + if (!_time_disagree || labs(offset - _time_disagree_offset) > GPS_GUARD_ALERT_TOLERANCE) { + _time_disagree = true; + _time_disagree_offset = offset; + _time_disagree_since_ms = now; + _time_alert = false; + return; + } + if (!_time_alert && (uint32_t)(now - _time_disagree_since_ms) >= GPS_GUARD_ALERT_MIN * 60000UL) { + _time_alert = true; + MESH_DEBUG_PRINTLN("GPS TIME ALERT: GPS differs from clock by %lds for %u min", offset, GPS_GUARD_ALERT_MIN); + } + } + +public: + // Plausible GPS time window: not before this firmware was built, at most 10 years after. + static uint32_t minEpoch() { + static const uint32_t min_epoch = DateTime(__DATE__, __TIME__).unixtime() - 86400; + return min_epoch; + } + static uint32_t maxEpoch() { return minEpoch() + 10UL * 365 * 86400; } + + void setReference(double lat, double lon) { _ref_lat = lat; _ref_lon = lon; } + double getRefLat() const { return _ref_lat; } + double getRefLon() const { return _ref_lon; } + void setFence(uint32_t metres) { _fence_m = metres; } + uint32_t getFence() const { return _fence_m; } + bool hasTrustedFix() const { return _have_trusted; } + bool isTimeAlert() const { return _time_alert; } + long getAlertOffset() const { return _time_disagree_offset; } + + // Fix as reported by the receiver: lat/lon in micro-degrees, HDOP in tenths (255 = unknown), + // gps_time = UTC epoch of the fix. Returns true if the fix can be stored as trusted. + bool acceptFix(long lat_e6, long lon_e6, long sats, uint8_t hdop10, uint32_t gps_time) { + const double lat = lat_e6 / 1000000.0; + const double lon = lon_e6 / 1000000.0; + const unsigned long now = millis(); + + const char* why = NULL; + double dist = 0; + if (sats < GPS_GUARD_MIN_SATS) { + why = "sats"; + } else if (hdop10 == 255 || hdop10 > GPS_GUARD_MAX_HDOP10) { + why = "hdop"; + } +#if defined(GPS_GUARD_LAT_MIN) && defined(GPS_GUARD_LAT_MAX) && defined(GPS_GUARD_LON_MIN) && defined(GPS_GUARD_LON_MAX) + else if (lat < GPS_GUARD_LAT_MIN || lat > GPS_GUARD_LAT_MAX || lon < GPS_GUARD_LON_MIN || lon > GPS_GUARD_LON_MAX) { + why = "region"; + } +#endif + else if (_fence_m > 0 && (_ref_lat != 0 || _ref_lon != 0) && + (dist = distanceM(_ref_lat, _ref_lon, lat, lon)) > _fence_m) { + why = "fence"; + } else if (_have_trusted) { + dist = distanceM(_last_trusted_lat, _last_trusted_lon, lat, lon); + double secs = (uint32_t)(now - _last_trusted_ms) / 1000.0; + if (secs < 1) secs = 1; + if (dist / secs > GPS_GUARD_MAX_SPEED_KMH / 3.6) why = "jump"; + } + + if (why) { + _stable_count = 0; + if (dist > 0) { + snprintf(_fix_status, sizeof(_fix_status), "rej %s %.1fkm", why, dist / 1000.0); + } else { + snprintf(_fix_status, sizeof(_fix_status), "rej %s", why); + } + if (gps_time == 0 || gps_time != _rej_log_time) { // GGA and RMC report the same second: log it once + _rej_log_time = gps_time; + MESH_DEBUG_PRINTLN("GPS fix rejected (%s): %f,%f sats=%ld hdop=%u", why, lat, lon, sats, hdop10); + } + return false; + } + + if (!_have_trusted || _stable_count < GPS_GUARD_STABLE_FIXES) { + // Require several consecutive, mutually consistent fixes. GGA and RMC report the + // same GPS second: count each second once. + if (_stable_count > 0 && distanceM(_cand_lat, _cand_lon, lat, lon) > GPS_GUARD_STABLE_M) { + _stable_count = 0; + } + if (_stable_count == 0 || gps_time != _cand_time) { + if (_stable_count < 255) _stable_count++; + } + _cand_lat = lat; + _cand_lon = lon; + _cand_time = gps_time; + if (_stable_count < GPS_GUARD_STABLE_FIXES) { + snprintf(_fix_status, sizeof(_fix_status), "settle %u/%u", _stable_count, GPS_GUARD_STABLE_FIXES); + return false; + } + } + + if (!_have_trusted) { + MESH_DEBUG_PRINTLN("GPS fix trusted: %f,%f sats=%ld hdop=%u", lat, lon, sats, hdop10); + } + _have_trusted = true; + _last_trusted_ms = now; + _last_trusted_lat = lat; + _last_trusted_lon = lon; + snprintf(_fix_status, sizeof(_fix_status), "ok %ldsat", sats); + return true; + } + + // No usable fix right now (e.g. receiver lost the fix): restart the consistency count. + void noFix(long sats) { + _stable_count = 0; + snprintf(_fix_status, sizeof(_fix_status), "no fix %ldsat", sats); + } + + // GPS time is only written to the clock while a trusted fix is current, it is not + // older than this firmware, and (once the clock is valid) it only nudges the clock. + bool acceptTime(uint32_t gps_time, uint32_t clock_time) { + const char* why = NULL; + long step = 0; + if (!trustedFixIsCurrent()) { + why = "nofix"; + } else if (gps_time < minEpoch() || gps_time > maxEpoch()) { + why = "range"; + } else if (clock_time >= minEpoch()) { // clock already holds a plausible time + step = (long)gps_time - (long)clock_time; + long limit = GPS_GUARD_TIME_MAX_STEP; + if (_time_accepted) { + // After the first accepted sync only allow corrections the size of real clock + // drift, so a spoofer cannot walk the clock away in many small steps. + uint32_t elapsed_s = (uint32_t)(millis() - _last_time_accept_ms) / 1000; + limit = GPS_GUARD_TIME_DRIFT_BASE + (long)((uint64_t)elapsed_s * GPS_GUARD_TIME_DRIFT_PPM / 1000000UL); + if (limit > GPS_GUARD_TIME_MAX_STEP) limit = GPS_GUARD_TIME_MAX_STEP; + } + if (labs(step) > limit) why = "step"; + } + + if (why) { + if (step != 0) { + snprintf(_time_status, sizeof(_time_status), "rej %s %lds", why, step); + trackTimeDisagreement(step); + } else { + snprintf(_time_status, sizeof(_time_status), "rej %s", why); + } + return false; + } + snprintf(_time_status, sizeof(_time_status), "ok %+lds", (long)gps_time - (long)clock_time); + // Every accepted sync anchors the drift budget (fail closed: no walking the clock in + // repeated MAX_STEP jumps). A wrongly anchored time is recovered with a manual clock + // set, which resets the anchor (clockSetManually()). + _time_disagree = false; + _time_alert = false; + _time_accepted = true; + _last_time_accept_ms = millis(); + return true; + } + + // The clock was set by hand: drop the drift anchor and any alert. + void clockSetManually() { + _time_accepted = false; + _time_disagree = false; + _time_alert = false; + } + + // Operator confirms that the alerted GPS time is right. offset = current GPS minus clock. + // Returns true if the caller may write the GPS time to the clock now. + bool acceptAlertedTime(long offset, uint32_t gps_time) { + if (!_time_alert || !trustedFixIsCurrent()) return false; + if (labs(offset - _time_disagree_offset) > GPS_GUARD_ALERT_TOLERANCE) return false; // not the alerted offset + if (gps_time < minEpoch() || gps_time > maxEpoch()) return false; + _time_accepted = true; + _last_time_accept_ms = millis(); + _time_disagree = false; + _time_alert = false; + snprintf(_time_status, sizeof(_time_status), "ok manual"); + return true; + } + + // e.g. "ok 7sat time ok +1s", "rej region time rej nofix", + // "ok 9sat time rej step 3600s ALERT gps-clk +3600s 75m" + void formatStatus(char* out, size_t out_size) const { + if (_time_alert) { + snprintf(out, out_size, "%s time %s ALERT gps-clk %+lds %lum", _fix_status, _time_status, + _time_disagree_offset, (unsigned long)((uint32_t)(millis() - _time_disagree_since_ms) / 60000)); + } else { + snprintf(out, out_size, "%s time %s", _fix_status, _time_status); + } + } +}; diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index 52093d872..5b5b69c04 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -5,6 +5,8 @@ #include +class GpsGuard; + class LocationProvider { public: // Last valid fix, always filled in one go so readers get a consistent snapshot. @@ -105,6 +107,11 @@ public: // Format compact diagnostics in the caller-provided buffer. Providers that // have more information (for example UART counters) can override this. + // Anti-spoofing guard (GPS_GUARD), nullptr if this provider has none + virtual GpsGuard* getGuard() { return nullptr; } + virtual bool getClockOffset(long& offset) { return false; } // GPS time minus clock time + virtual bool applyTimeNow() { return false; } // write GPS time to the clock now + virtual void formatDiagnostics(char* out, size_t out_size) { if (out_size == 0) return; snprintf(out, out_size, "en:%u sat:%ld fix:%u", diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index f3442bd5d..bc9f5efa7 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -5,6 +5,9 @@ #include #include #include +#ifdef GPS_GUARD +#include "GpsGuard.h" +#endif #ifndef GPS_PERIODIC_ACQUISITION_TIMEOUT_MS #define GPS_PERIODIC_ACQUISITION_TIMEOUT_MS 300000UL @@ -44,6 +47,9 @@ class MicroNMEALocationProvider : public LocationProvider { unsigned long _last_nmea_ms = 0; bool _uart_seen = false; bool _nmea_seen = false; +#ifdef GPS_GUARD + GpsGuard _guard; +#endif static uint32_t ageMs(unsigned long timestamp) { return (uint32_t)(millis() - timestamp); @@ -80,6 +86,11 @@ class MicroNMEALocationProvider : public LocationProvider { // only store a fix when the snapshot is coherent (sats > 0). // Returns true if the fix was stored. if (nmea.getNumSatellites() == 0) return false; +#ifdef GPS_GUARD + // only plausible, stable fixes become the last fix (position, telemetry, time sync) + if (!_guard.acceptFix(nmea.getLatitude(), nmea.getLongitude(), nmea.getNumSatellites(), + nmea.getHDOP(), getTimestamp())) return false; +#endif LastFix fix; fix.latitude = nmea.getLatitude(); @@ -106,7 +117,7 @@ class MicroNMEALocationProvider : public LocationProvider { (millis() - _last_time_sync) > TIME_SYNC_INTERVAL) { _time_sync_needed = true; } - if (_time_sync_needed && time_valid > 2 && _clock != nullptr) { + if (_time_sync_needed && time_valid > 2 && _clock != nullptr && timeSyncAllowed()) { _clock->setCurrentTime(getTimestamp()); _time_sync_needed = false; _last_time_sync = millis(); @@ -114,6 +125,14 @@ class MicroNMEALocationProvider : public LocationProvider { if (isValid()) time_valid++; } + bool timeSyncAllowed() { +#ifdef GPS_GUARD + return _guard.acceptTime(getTimestamp(), _clock->getCurrentTime()); +#else + return true; +#endif + } + public: MicroNMEALocationProvider(NmeaGpsDriver& driver, mesh::RTCClock* clock = nullptr) : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), _driver(&driver) {} @@ -195,7 +214,15 @@ public: } // Position, altitude and satellite count describe the last saved fix - // Before the first saved fix, fall back to the live parser state. + // Before the first saved fix, fall back to the live parser state + // (not with GPS_GUARD: an unverified position is never reported). +#ifdef GPS_GUARD + GpsGuard* getGuard() override { return &_guard; } + bool hasValidFix() override { return _lastFix.valid; } + long getLatitude() override { return _lastFix.latitude; } + long getLongitude() override { return _lastFix.longitude; } + long getAltitude() override { return _lastFix.altitude; } +#else long getLatitude() override { return _lastFix.valid ? _lastFix.latitude : nmea.getLatitude(); } @@ -208,6 +235,23 @@ public: nmea.getAltitude(alt); return alt; } +#endif + + // GPS time minus clock time, from a current fix with a settled time + bool getClockOffset(long& offset) override { + if (_clock == nullptr || !isValid() || time_valid < 3) return false; + offset = (long)getTimestamp() - (long)_clock->getCurrentTime(); + return true; + } + + // write the current GPS time to the clock now (caller has done its own checks) + bool applyTimeNow() override { + if (_clock == nullptr || !isValid() || time_valid < 3) return false; + _clock->setCurrentTime(getTimestamp()); + _time_sync_needed = false; + _last_time_sync = millis(); + return true; + } long satellitesCount() override { return _lastFix.valid ? _lastFix.satellites : nmea.getNumSatellites(); } @@ -286,6 +330,12 @@ public: _nmea_seen = true; const char* messageId = nmea.getMessageID(); +#ifdef GPS_GUARD + if (parsed && !nmea.isValid() && + (strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) { + _guard.noFix(nmea.getNumSatellites()); + } +#endif if (parsed && nmea.isValid() && (strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) { if (!saveFix()) continue; // incoherent snapshot diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h index 903546ba5..2dda12a51 100644 --- a/src/helpers/sensors/RakLocationProvider.h +++ b/src/helpers/sensors/RakLocationProvider.h @@ -71,6 +71,23 @@ public: return _useI2c ? _lastFix.timestamp : _nmea.getTimestamp(); } + // the anti-spoofing guard (GPS_GUARD) only covers the serial NMEA path + GpsGuard* getGuard() override { + return _useI2c ? nullptr : _nmea.getGuard(); + } + + bool hasValidFix() override { + return _useI2c ? LocationProvider::hasValidFix() : _nmea.hasValidFix(); + } + + bool getClockOffset(long& offset) override { + return _useI2c ? false : _nmea.getClockOffset(offset); + } + + bool applyTimeNow() override { + return _useI2c ? false : _nmea.applyTimeNow(); + } + void sendSentence(const char* sentence) override { if (!_useI2c) _nmea.sendSentence(sentence); } From 181041ac6408ad17d62f531b823e85fdad333936 Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko Date: Mon, 9 Nov 2026 22:15:45 +0200 Subject: [PATCH 2/6] GpsGuard: do not show a stale time ok without a current trusted fix --- src/helpers/sensors/GpsGuard.h | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/helpers/sensors/GpsGuard.h b/src/helpers/sensors/GpsGuard.h index 238bc7e88..eed387bab 100644 --- a/src/helpers/sensors/GpsGuard.h +++ b/src/helpers/sensors/GpsGuard.h @@ -265,11 +265,14 @@ public: // e.g. "ok 7sat time ok +1s", "rej region time rej nofix", // "ok 9sat time rej step 3600s ALERT gps-clk +3600s 75m" void formatStatus(char* out, size_t out_size) const { + // The time status is only refreshed when a sync is due: without a current trusted fix, + // do not keep showing an old "ok" as if GPS time were usable now. + const char* time_status = (_time_status[0] == 'o' && !trustedFixIsCurrent()) ? "rej nofix" : _time_status; if (_time_alert) { - snprintf(out, out_size, "%s time %s ALERT gps-clk %+lds %lum", _fix_status, _time_status, + snprintf(out, out_size, "%s time %s ALERT gps-clk %+lds %lum", _fix_status, time_status, _time_disagree_offset, (unsigned long)((uint32_t)(millis() - _time_disagree_since_ms) / 60000)); } else { - snprintf(out, out_size, "%s time %s", _fix_status, _time_status); + snprintf(out, out_size, "%s time %s", _fix_status, time_status); } } }; From eea64ffb743c58be14aa8277e250f87e97ebad81 Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko Date: Mon, 9 Nov 2026 22:30:24 +0200 Subject: [PATCH 3/6] GPS guard: drop time force, it goes to a separate PR --- docs/cli_commands.md | 4 +--- src/helpers/CommonCLI.cpp | 10 ---------- 2 files changed, 1 insertion(+), 13 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index e21b6a8ea..69a1347e5 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -69,8 +69,6 @@ This document provides an overview of CLI commands that can be sent to MeshCore **Parameters:** - `epoch_seconds`: Unix epoch time -**Note:** The clock only moves forward. To set it back (e.g. after the clock was pushed into the future by a wrong GPS time) use `time force `. - --- ### Send a flood advert @@ -1082,7 +1080,7 @@ region save #### GPS anti-spoofing guard (When built with `GPS_GUARD`) With `GPS_GUARD`, a fix becomes the node's last fix (position, telemetry, adverts) only after it passes plausibility checks: at least `GPS_GUARD_MIN_SATS` satellites, HDOP ≤ `GPS_GUARD_MAX_HDOP10`/10, inside the optional build-time region (`GPS_GUARD_LAT_MIN/MAX`, `GPS_GUARD_LON_MIN/MAX`), within the fence around the node's configured `lat`/`lon` (if set), no jump faster than `GPS_GUARD_MAX_SPEED_KMH`, and `GPS_GUARD_STABLE_FIXES` consistent fixes in a row. An unverified position is never reported. -GPS time is written to the clock only while such a fix is current, never earlier than the firmware build date, and, once the clock is valid, only within `GPS_GUARD_TIME_MAX_STEP` seconds for the first sync and within clock drift (`GPS_GUARD_TIME_DRIFT_BASE` s + `GPS_GUARD_TIME_DRIFT_PPM`) afterwards. Setting the clock manually (`time`, `time force`, `clock sync`) resets that anchor. +GPS time is written to the clock only while such a fix is current, never earlier than the firmware build date, and, once the clock is valid, only within `GPS_GUARD_TIME_MAX_STEP` seconds for the first sync and within clock drift (`GPS_GUARD_TIME_DRIFT_BASE` s + `GPS_GUARD_TIME_DRIFT_PPM`) afterwards. Setting the clock manually (`time`, `clock sync`) resets that anchor. Covers serial NMEA receivers (`MicroNMEALocationProvider`). diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index fa3ad7897..2c79bae16 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -226,16 +226,6 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re uint32_t now = getRTCClock()->getCurrentTime(); DateTime dt = DateTime(now); sprintf(reply, "%02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year()); - } else if (memcmp(command, "time force ", 11) == 0) { // set time, allowing it to go backwards - uint32_t secs = _atoi(&command[11]); - if (secs > 1700000000UL) { - getRTCClock()->setCurrentTime(secs); - CommonGpsPrefs::onClockSetManually(*_sensors); - DateTime dt = DateTime(getRTCClock()->getCurrentTime()); - sprintf(reply, "OK - clock forced: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year()); - } else { - strcpy(reply, "ERR: invalid epoch"); - } } else if (memcmp(command, "time ", 5) == 0) { // set time (to epoch seconds) uint32_t secs = _atoi(&command[5]); uint32_t curr = getRTCClock()->getCurrentTime(); From fbd20ac64b00bf7653aca05b97f26da4f8918c99 Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko Date: Mon, 9 Nov 2026 22:54:18 +0200 Subject: [PATCH 4/6] GpsGuard: let GPS correct a clock outside the plausible window --- docs/cli_commands.md | 2 +- src/helpers/sensors/GpsGuard.h | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 69a1347e5..babd7102b 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1080,7 +1080,7 @@ region save #### GPS anti-spoofing guard (When built with `GPS_GUARD`) With `GPS_GUARD`, a fix becomes the node's last fix (position, telemetry, adverts) only after it passes plausibility checks: at least `GPS_GUARD_MIN_SATS` satellites, HDOP ≤ `GPS_GUARD_MAX_HDOP10`/10, inside the optional build-time region (`GPS_GUARD_LAT_MIN/MAX`, `GPS_GUARD_LON_MIN/MAX`), within the fence around the node's configured `lat`/`lon` (if set), no jump faster than `GPS_GUARD_MAX_SPEED_KMH`, and `GPS_GUARD_STABLE_FIXES` consistent fixes in a row. An unverified position is never reported. -GPS time is written to the clock only while such a fix is current, never earlier than the firmware build date, and, once the clock is valid, only within `GPS_GUARD_TIME_MAX_STEP` seconds for the first sync and within clock drift (`GPS_GUARD_TIME_DRIFT_BASE` s + `GPS_GUARD_TIME_DRIFT_PPM`) afterwards. Setting the clock manually (`time`, `clock sync`) resets that anchor. +GPS time is written to the clock only while such a fix is current, never earlier than the firmware build date, and, once the clock holds a plausible time (from the build date to 10 years after it), only within `GPS_GUARD_TIME_MAX_STEP` seconds for the first sync and within clock drift (`GPS_GUARD_TIME_DRIFT_BASE` s + `GPS_GUARD_TIME_DRIFT_PPM`) afterwards. Setting the clock manually (`time`, `clock sync`) resets that anchor. A clock outside that window (e.g. a bogus date in 2080) is corrected by the first trusted fix. Covers serial NMEA receivers (`MicroNMEALocationProvider`). diff --git a/src/helpers/sensors/GpsGuard.h b/src/helpers/sensors/GpsGuard.h index eed387bab..bd26aee03 100644 --- a/src/helpers/sensors/GpsGuard.h +++ b/src/helpers/sensors/GpsGuard.h @@ -200,7 +200,7 @@ public: } // GPS time is only written to the clock while a trusted fix is current, it is not - // older than this firmware, and (once the clock is valid) it only nudges the clock. + // older than this firmware, and (once the clock is plausible) it only nudges the clock. bool acceptTime(uint32_t gps_time, uint32_t clock_time) { const char* why = NULL; long step = 0; @@ -208,7 +208,9 @@ public: why = "nofix"; } else if (gps_time < minEpoch() || gps_time > maxEpoch()) { why = "range"; - } else if (clock_time >= minEpoch()) { // clock already holds a plausible time + } else if (clock_time >= minEpoch() && clock_time <= maxEpoch()) { + // The clock already holds a plausible time. A clock outside that window (e.g. a + // bogus 2080 date at boot) is treated like an unset one, so GPS can correct it. step = (long)gps_time - (long)clock_time; long limit = GPS_GUARD_TIME_MAX_STEP; if (_time_accepted) { From d72f67d37bf951402ea328baf13219b4712ad6ef Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko Date: Mon, 9 Nov 2026 23:16:29 +0200 Subject: [PATCH 5/6] GPS guard: save gps fence in the GPS prefs --- docs/cli_commands.md | 2 +- examples/companion_radio/NodePrefs.h | 10 ++++++++++ src/helpers/CommonCLI.h | 10 ++++++++++ src/helpers/CommonGpsPrefs.cpp | 5 ++++- src/helpers/CommonGpsPrefs.h | 3 +++ 5 files changed, 28 insertions(+), 2 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index babd7102b..74db9e5ce 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1087,7 +1087,7 @@ Covers serial NMEA receivers (`MicroNMEALocationProvider`). **Usage:** - `gps guard`: status, e.g. `> ok 7sat time ok +1s`, `> rej region time rej nofix`, or `... ALERT gps-clk +3600s 75m` when a trusted fix has disagreed with the clock by the same offset for `GPS_GUARD_ALERT_MIN` minutes. While the alert is active, the offset in hours is also reported in telemetry on the next free channel. - `gps guard accept`: while an alert is active, confirm that the GPS time is right and apply it to the clock. -- `gps fence`, `gps fence `: fence radius around the configured `lat`/`lon` (`0` = off). Default `GPS_GUARD_FENCE_M` (1000), not saved. +- `gps fence`, `gps fence `: fence radius around the configured `lat`/`lon` (`0` = off). Default `GPS_GUARD_FENCE_M` (1000); a value set here is saved. - `gps ref`: the reference position; follows `set lat`, `set lon` and `gps setloc`. --- diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index db019370b..7758354a6 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -37,6 +37,7 @@ public: uint8_t gps_enabled = 0; // GPS enabled flag (0=disabled, 1=enabled) uint32_t gps_interval = 0; // GPS read interval in seconds uint32_t gps_period = 0; // periodic acquisition interval in seconds + int32_t gps_fence = -1; // GPS_GUARD fence in metres, 0 = off, -1 = build default uint8_t autoadd_config = 0; // bitmask for auto-add contacts config uint8_t rx_boosted_gain = 0; // SX126x RX boosted gain mode (0=power saving, 1=boosted) uint8_t radio_fem_rxgain = 0; // external LoRa FEM RX gain (LNA) @@ -166,6 +167,9 @@ private: def("int", _parent->gps_interval); // interval in seconds def("period", _parent->gps_period); // periodic acquisition interval in seconds def("adv_loc", _parent->advert_loc_policy); +#ifdef GPS_GUARD + def("fence", _parent->gps_fence); +#endif } public: GPSPrefs(NodePrefs* parent) : _parent(parent) { } @@ -173,6 +177,12 @@ private: void setGpsEnabled(bool enabled) override { _parent->gps_enabled = enabled; markDirty(); } uint32_t getGpsPeriod() const override { return _parent->gps_period; } void setGpsPeriod(uint32_t seconds) override { _parent->gps_period = seconds; markDirty(); } + bool getGuardFence(uint32_t& metres) const override { + if (_parent->gps_fence < 0) return false; + metres = (uint32_t)_parent->gps_fence; + return true; + } + void setGuardFence(uint32_t metres) override { _parent->gps_fence = (int32_t)metres; markDirty(); } }; GPSPrefs gps; diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 823f6c0fd..fa39d587c 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -63,6 +63,7 @@ public: uint8_t gps_enabled = 0; uint32_t gps_interval = 0; // in seconds uint32_t gps_period = 0; // periodic acquisition interval in seconds + int32_t gps_fence = -1; // GPS_GUARD fence in metres, 0 = off, -1 = build default uint8_t advert_loc_policy = 0; uint32_t discovery_mod_timestamp = 0; float adc_multiplier = 0; @@ -162,6 +163,9 @@ private: def("int", _parent->gps_interval); // interval in seconds def("period", _parent->gps_period); // periodic acquisition interval in seconds def("adv_loc", _parent->advert_loc_policy); +#ifdef GPS_GUARD + def("fence", _parent->gps_fence); +#endif } public: GPSPrefs(NodePrefs* parent) : _parent(parent) { } @@ -169,6 +173,12 @@ private: void setGpsEnabled(bool enabled) override { _parent->gps_enabled = enabled; markDirty(); } uint32_t getGpsPeriod() const override { return _parent->gps_period; } void setGpsPeriod(uint32_t seconds) override { _parent->gps_period = seconds; markDirty(); } + bool getGuardFence(uint32_t& metres) const override { + if (_parent->gps_fence < 0) return false; + metres = (uint32_t)_parent->gps_fence; + return true; + } + void setGuardFence(uint32_t metres) override { _parent->gps_fence = (int32_t)metres; markDirty(); } bool getGuardReference(double& lat, double& lon) const override { lat = _parent->node_lat; lon = _parent->node_lon; diff --git a/src/helpers/CommonGpsPrefs.cpp b/src/helpers/CommonGpsPrefs.cpp index 8faf01a65..161775595 100644 --- a/src/helpers/CommonGpsPrefs.cpp +++ b/src/helpers/CommonGpsPrefs.cpp @@ -26,6 +26,8 @@ void CommonGpsPrefs::applyGuardReference(SensorManager& sensors) const { GpsGuard* guard = location != nullptr ? location->getGuard() : nullptr; double lat, lon; if (guard != nullptr && getGuardReference(lat, lon)) guard->setReference(lat, lon); + uint32_t fence; + if (guard != nullptr && getGuardFence(fence)) guard->setFence(fence); #endif } @@ -247,10 +249,11 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, } else if (memcmp(command, "gps fence ", 10) == 0) { char* end; unsigned long metres = strtoul(command + 10, &end, 10); - if (command[10] == '' || *end != '') { + if (command[10] == '\0' || *end != '\0' || metres > 20000000UL) { // at most half the Earth strcpy(reply, "Error, invalid fence"); } else { guard->setFence((uint32_t)metres); + setGuardFence((uint32_t)metres); // saved by the caller (isDirty) strcpy(reply, "OK"); } } else if (strcmp(command, "gps ref") == 0) { diff --git a/src/helpers/CommonGpsPrefs.h b/src/helpers/CommonGpsPrefs.h index 7a7d57447..3fa1c9b2a 100644 --- a/src/helpers/CommonGpsPrefs.h +++ b/src/helpers/CommonGpsPrefs.h @@ -21,6 +21,9 @@ public: // Reference position for the anti-spoofing guard (GPS_GUARD), e.g. the configured node position. virtual bool getGuardReference(double& lat, double& lon) const { return false; } + // Saved fence radius for the guard; false = not set, use the build default. + virtual bool getGuardFence(uint32_t& metres) const { return false; } + virtual void setGuardFence(uint32_t metres) { } bool setGpsEnabled(SensorManager& sensors, bool enabled); void applyGuardReference(SensorManager& sensors) const; From 8c7e1a8f5d5afd973dca9510a8e4c0ff4acfa429 Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko Date: Mon, 9 Nov 2026 23:50:48 +0200 Subject: [PATCH 6/6] GPS guard: gps guard on/off, saved in the GPS prefs --- docs/cli_commands.md | 1 + examples/companion_radio/NodePrefs.h | 7 +++++++ src/helpers/CommonCLI.h | 7 +++++++ src/helpers/CommonGpsPrefs.cpp | 7 +++++++ src/helpers/CommonGpsPrefs.h | 3 +++ src/helpers/sensors/GpsGuard.h | 20 ++++++++++++++++++++ 6 files changed, 45 insertions(+) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 74db9e5ce..754f51201 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1086,6 +1086,7 @@ Covers serial NMEA receivers (`MicroNMEALocationProvider`). **Usage:** - `gps guard`: status, e.g. `> ok 7sat time ok +1s`, `> rej region time rej nofix`, or `... ALERT gps-clk +3600s 75m` when a trusted fix has disagreed with the clock by the same offset for `GPS_GUARD_ALERT_MIN` minutes. While the alert is active, the offset in hours is also reported in telemetry on the next free channel. +- `gps guard on`, `gps guard off`: turn the guard on or off (saved, default on). While off, every fix and GPS time is accepted and `gps guard` shows `off`. - `gps guard accept`: while an alert is active, confirm that the GPS time is right and apply it to the clock. - `gps fence`, `gps fence `: fence radius around the configured `lat`/`lon` (`0` = off). Default `GPS_GUARD_FENCE_M` (1000); a value set here is saved. - `gps ref`: the reference position; follows `set lat`, `set lon` and `gps setloc`. diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index 7758354a6..6aa3d47c8 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -38,6 +38,7 @@ public: uint32_t gps_interval = 0; // GPS read interval in seconds uint32_t gps_period = 0; // periodic acquisition interval in seconds int32_t gps_fence = -1; // GPS_GUARD fence in metres, 0 = off, -1 = build default + uint8_t gps_guard = 1; // GPS_GUARD on/off uint8_t autoadd_config = 0; // bitmask for auto-add contacts config uint8_t rx_boosted_gain = 0; // SX126x RX boosted gain mode (0=power saving, 1=boosted) uint8_t radio_fem_rxgain = 0; // external LoRa FEM RX gain (LNA) @@ -169,6 +170,7 @@ private: def("adv_loc", _parent->advert_loc_policy); #ifdef GPS_GUARD def("fence", _parent->gps_fence); + def("guard", _parent->gps_guard); #endif } public: @@ -183,6 +185,11 @@ private: return true; } void setGuardFence(uint32_t metres) override { _parent->gps_fence = (int32_t)metres; markDirty(); } + bool getGuardEnabled(bool& enabled) const override { + enabled = _parent->gps_guard != 0; + return true; + } + void setGuardEnabled(bool enabled) override { _parent->gps_guard = enabled ? 1 : 0; markDirty(); } }; GPSPrefs gps; diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index fa39d587c..cb85f6f99 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -64,6 +64,7 @@ public: uint32_t gps_interval = 0; // in seconds uint32_t gps_period = 0; // periodic acquisition interval in seconds int32_t gps_fence = -1; // GPS_GUARD fence in metres, 0 = off, -1 = build default + uint8_t gps_guard = 1; // GPS_GUARD on/off uint8_t advert_loc_policy = 0; uint32_t discovery_mod_timestamp = 0; float adc_multiplier = 0; @@ -165,6 +166,7 @@ private: def("adv_loc", _parent->advert_loc_policy); #ifdef GPS_GUARD def("fence", _parent->gps_fence); + def("guard", _parent->gps_guard); #endif } public: @@ -179,6 +181,11 @@ private: return true; } void setGuardFence(uint32_t metres) override { _parent->gps_fence = (int32_t)metres; markDirty(); } + bool getGuardEnabled(bool& enabled) const override { + enabled = _parent->gps_guard != 0; + return true; + } + void setGuardEnabled(bool enabled) override { _parent->gps_guard = enabled ? 1 : 0; markDirty(); } bool getGuardReference(double& lat, double& lon) const override { lat = _parent->node_lat; lon = _parent->node_lon; diff --git a/src/helpers/CommonGpsPrefs.cpp b/src/helpers/CommonGpsPrefs.cpp index 161775595..cdc889d00 100644 --- a/src/helpers/CommonGpsPrefs.cpp +++ b/src/helpers/CommonGpsPrefs.cpp @@ -28,6 +28,8 @@ void CommonGpsPrefs::applyGuardReference(SensorManager& sensors) const { if (guard != nullptr && getGuardReference(lat, lon)) guard->setReference(lat, lon); uint32_t fence; if (guard != nullptr && getGuardFence(fence)) guard->setFence(fence); + bool enabled; + if (guard != nullptr && getGuardEnabled(enabled)) guard->setEnabled(enabled); #endif } @@ -232,6 +234,11 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, } else if (strcmp(command, "gps guard") == 0) { reply[0] = '>'; reply[1] = ' '; guard->formatStatus(reply + 2, 158); + } else if (strcmp(command, "gps guard on") == 0 || strcmp(command, "gps guard off") == 0) { + const bool enabled = command[11] == 'n'; + guard->setEnabled(enabled); + setGuardEnabled(enabled); // saved by the caller (isDirty) + strcpy(reply, "OK"); } else if (strcmp(command, "gps guard accept") == 0) { // operator confirms that the alerted GPS time is right: apply it to the clock long offset; diff --git a/src/helpers/CommonGpsPrefs.h b/src/helpers/CommonGpsPrefs.h index 3fa1c9b2a..c1e30b8ea 100644 --- a/src/helpers/CommonGpsPrefs.h +++ b/src/helpers/CommonGpsPrefs.h @@ -24,6 +24,9 @@ public: // Saved fence radius for the guard; false = not set, use the build default. virtual bool getGuardFence(uint32_t& metres) const { return false; } virtual void setGuardFence(uint32_t metres) { } + // Saved on/off state of the guard; false = not set, guard on. + virtual bool getGuardEnabled(bool& enabled) const { return false; } + virtual void setGuardEnabled(bool enabled) { } bool setGpsEnabled(SensorManager& sensors, bool enabled); void applyGuardReference(SensorManager& sensors) const; diff --git a/src/helpers/sensors/GpsGuard.h b/src/helpers/sensors/GpsGuard.h index bd26aee03..cf7130333 100644 --- a/src/helpers/sensors/GpsGuard.h +++ b/src/helpers/sensors/GpsGuard.h @@ -57,6 +57,7 @@ #endif class GpsGuard { + bool _enabled = true; // off: every fix and GPS time passes, as without GPS_GUARD double _ref_lat = 0, _ref_lon = 0; // 0,0 = no reference position uint32_t _fence_m = GPS_GUARD_FENCE_M; @@ -118,6 +119,19 @@ public: void setFence(uint32_t metres) { _fence_m = metres; } uint32_t getFence() const { return _fence_m; } bool hasTrustedFix() const { return _have_trusted; } + bool isEnabled() const { return _enabled; } + void setEnabled(bool enabled) { + if (enabled == _enabled) return; + _enabled = enabled; + // start over: a re-enabled guard needs fresh stable fixes, and no alert survives + _have_trusted = false; + _stable_count = 0; + _time_accepted = false; + _time_disagree = false; + _time_alert = false; + strcpy(_fix_status, "no fix"); + strcpy(_time_status, "-"); + } bool isTimeAlert() const { return _time_alert; } long getAlertOffset() const { return _time_disagree_offset; } @@ -127,6 +141,7 @@ public: const double lat = lat_e6 / 1000000.0; const double lon = lon_e6 / 1000000.0; const unsigned long now = millis(); + if (!_enabled) return true; const char* why = NULL; double dist = 0; @@ -202,6 +217,7 @@ public: // GPS time is only written to the clock while a trusted fix is current, it is not // older than this firmware, and (once the clock is plausible) it only nudges the clock. bool acceptTime(uint32_t gps_time, uint32_t clock_time) { + if (!_enabled) return true; const char* why = NULL; long step = 0; if (!trustedFixIsCurrent()) { @@ -267,6 +283,10 @@ public: // e.g. "ok 7sat time ok +1s", "rej region time rej nofix", // "ok 9sat time rej step 3600s ALERT gps-clk +3600s 75m" void formatStatus(char* out, size_t out_size) const { + if (!_enabled) { + snprintf(out, out_size, "off"); + return; + } // The time status is only refreshed when a sync is due: without a current trusted fix, // do not keep showing an old "ok" as if GPS time were usable now. const char* time_status = (_time_status[0] == 'o' && !trustedFixIsCurrent()) ? "rej nofix" : _time_status;