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.
This commit is contained in:
Olexandr Tyshchenko committed 2026-11-09 20:43:09 +02:00
1 parent 017005d1cf
commit 6b3da8a2b1
10 files changed
+466 -2

No files matched your search

+17
View File
@@ -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 <epoch_seconds>`.
---
### 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 <metres>`: 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`
+15
View File
@@ -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) {
+5
View File
@@ -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;
+63
View File
@@ -1,5 +1,8 @@
#include "CommonGpsPrefs.h"
#include <helpers/sensors/LocationProvider.h>
#ifdef GPS_GUARD
#include <helpers/sensors/GpsGuard.h>
#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) {
+5
View File
@@ -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);
@@ -1,6 +1,9 @@
#include "EnvironmentSensorManager.h"
#include <Wire.h>
#if ENV_INCLUDE_GPS && defined(GPS_GUARD)
#include <helpers/sensors/GpsGuard.h>
#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;
+275
View File
@@ -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 <Arduino.h>
#include <MeshCore.h>
#include <RTClib.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#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);
}
}
};
+7
View File
@@ -5,6 +5,8 @@
#include <stdio.h>
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",
@@ -5,6 +5,9 @@
#include <MicroNMEA.h>
#include <RTClib.h>
#include <string.h>
#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
+17
View File
@@ -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);
}