QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
SigningController.cc
Go to the documentation of this file.
1#include "SigningController.h"
2
3#include <QtCore/QMetaEnum>
4#include <QtCore/QMetaObject>
5
6#include "MAVLinkLib.h"
7#include "MAVLinkSigning.h"
10#include "QGCMAVLink.h"
11#include "SecureMemory.h"
12
13QGC_LOGGING_CATEGORY(SigningControllerLog, "MAVLink.SigningController")
14
15namespace {
16
17const char* failReasonName(SigningController::FailReason r)
18{
19 return QMetaEnum::fromType<SigningFailure::Reason>().valueToKey(static_cast<int>(r));
20}
21
22} // namespace
23
25 : QObject(parent), _mavlinkChannel(channel)
26{
27 _timeout.setSingleShot(true);
28 connect(&_timeout, &QTimer::timeout, this, &SigningController::_onTimeout);
29 _wallClockRefresh.setInterval(kWallClockRefreshInterval);
30 connect(&_wallClockRefresh, &QTimer::timeout, this, [this]() { _channel.refreshOutgoingTimestamp(); });
31 qCDebug(SigningControllerLog) << "SigningController ctor — channel" << _mavlinkChannel;
32}
33
35{
36 qCDebug(SigningControllerLog) << "SigningController dtor — channel" << _mavlinkChannel;
37 _timeout.stop();
38 _wallClockRefresh.stop();
39 {
40 QMutexLocker<QRecursiveMutex> locker(&_fsmMutex);
41 _autoDetectGuard.reset();
42 if (_op.kind == OpKind::Enable) {
43 QGC::secureZero(_op.keyBytes);
44 }
45 _op = PendingOp{};
46 }
47
48 // Detach status->signing before _channel dies — otherwise the next parser call dangles.
49 _channel.init(_mavlinkChannel, QByteArrayView(), nullptr);
50}
51
52void SigningController::_setOpLocked(PendingOp next)
53{
54 _op = std::move(next);
55 QMetaObject::invokeMethod(this, [this]() { emit stateChanged(); }, Qt::AutoConnection);
56}
57
58void SigningController::_setWallClockRefresh(bool on)
59{
60 // QTimer start/stop must run on the timer's owning (main) thread; auto-detect reaches here on the link-RX thread.
61 QMetaObject::invokeMethod(&_wallClockRefresh, on ? "start" : "stop", Qt::AutoConnection);
62}
63
65{
66 OpKind kind;
67 {
68 QMutexLocker<QRecursiveMutex> locker(&_fsmMutex);
69 kind = _op.kind;
70 }
71 switch (kind) {
72 case OpKind::Enable:
73 return State::Enabling;
74 case OpKind::Disable:
75 return State::Disabling;
76 case OpKind::None:
77 break;
78 }
79 return _channel.isEnabled() ? State::On : State::Off;
80}
81
83{
85 s.state = state();
86 // Enabling installs the channel struct but isn't surfaced as enabled; Disabling stays enabled until vehicle
87 // confirms.
88 s.enabled = (s.state == State::On) || (s.state == State::Disabling);
89 s.keyName = _channel.keyHint();
91 s.streamCount = _channel.streamCount();
92 return s;
93}
94
96{
97 // Excludes Enabling: channel struct installed for verify but vehicle hasn't confirmed yet.
98 const State s = state();
99 return (s == State::On) || (s == State::Disabling);
100}
101
103{
104 return _channel.keyHint();
105}
106
108{
109 const State s = state();
110 if (s == State::Enabling) {
111 return tr("Configuring…");
112 }
113 if (s == State::Disabling) {
114 return tr("Disabling…");
115 }
116 if (!_channel.isEnabled()) {
117 return tr("Off");
118 }
119 // Last wire-status detail (empty when NONE); fall back to "On" for a healthy-but-idle link.
120 const QString detail = MAVLinkSigning::signingStatusString(_mavlinkChannel);
121 return detail.isEmpty() ? tr("On") : detail;
122}
123
125{
126 if (_channel.isEnabled()) {
127 const auto snap = _channel.currentTimestampAndName();
128 if (!snap.keyName.isEmpty() && snap.timestamp > 0) {
129 MAVLinkSigningKeys::instance()->recordTimestamp(snap.keyName, snap.timestamp);
130 }
131 }
132 const bool ok = _channel.init(_mavlinkChannel, QByteArrayView(), nullptr);
133 _channel.clearDetectCooldown();
134 _setWallClockRefresh(false);
135 return ok;
136}
137
139 const QString& keyNameHint)
140{
141 const uint64_t persisted = keyNameHint.isEmpty() ? 0 : MAVLinkSigningKeys::instance()->lastTimestamp(keyNameHint);
142 const bool ok = _channel.init(_mavlinkChannel, key, MAVLinkSigning::callbackForPolicy(policy), persisted, keyNameHint);
143 _setWallClockRefresh(_channel.isEnabled());
144 return ok;
145}
146
147std::optional<SigningFailure> SigningController::tryBeginEnable(quint32 expectedSysId, const QString& kName,
148 const MAVLinkSigning::SigningKey& keyBytes)
149{
150 {
151 QMutexLocker<QRecursiveMutex> locker(&_fsmMutex);
152 if (_isPendingLocked()) {
153 qCWarning(SigningControllerLog)
154 << "[ch" << _mavlinkChannel << "] enable rejected: operation already pending";
155 return SigningFailure{FailReason::VehicleUnreachable, tr("Signing operation already pending")};
156 }
157
158 // PendingEnableVerifyOnly: signOutgoing=false, lenient policy keeps non-responding vehicle observable while lib
159 // verifies its signed reply.
160 const QByteArrayView keyView(reinterpret_cast<const char*>(keyBytes.data()), keyBytes.size());
161 const uint64_t persisted = kName.isEmpty() ? 0 : MAVLinkSigningKeys::instance()->lastTimestamp(kName);
162 if (!_channel.init(_mavlinkChannel, keyView,
164 persisted, kName, /*signOutgoing=*/false)) {
165 qCWarning(SigningControllerLog) << "[ch" << _mavlinkChannel << "] enable rejected: signing init failed";
166 return SigningFailure{FailReason::InitFailed, tr("Failed to install signing for pending verification")};
167 }
168
169 _autoDetectGuard.emplace(_channel.suspendAutoDetect());
170 _setOpLocked(PendingOp{
171 .kind = OpKind::Enable,
172 .expectedSysId = expectedSysId,
173 .keyName = kName,
174 .keyBytes = keyBytes,
175 });
176 }
177 // QTimer is owned by main thread; tryBeginEnable is called on the main thread.
178 _timeout.setInterval(_effectiveTimeout());
179 _timeout.start();
180 _setWallClockRefresh(true); // channel installed (signOutgoing flips true on confirm); keep timestamp fresh meanwhile
181 qCDebug(SigningControllerLog) << "[ch" << _mavlinkChannel << "] enable pending — key" << kName << "sysid"
182 << expectedSysId << "timeout" << kTimeout << "ms";
183 return std::nullopt;
184}
185
186std::optional<SigningFailure> SigningController::tryBeginDisable(quint32 expectedSysId)
187{
188 {
189 QMutexLocker<QRecursiveMutex> locker(&_fsmMutex);
190 if (_isPendingLocked()) {
191 qCWarning(SigningControllerLog)
192 << "[ch" << _mavlinkChannel << "] disable rejected: operation already pending";
193 return SigningFailure{FailReason::VehicleUnreachable, tr("Signing operation already pending")};
194 }
195
196 if (!_channel.setAcceptUnsignedCallback(
198 qCWarning(SigningControllerLog) << "[ch" << _mavlinkChannel << "] disable rejected: channel not signing";
199 return SigningFailure{FailReason::VehicleUnreachable, tr("Channel not signing — cannot disable")};
200 }
201
202 _setOpLocked(PendingOp{
203 .kind = OpKind::Disable,
204 .expectedSysId = expectedSysId,
205 .keyName = {},
206 .keyBytes = {},
207 });
208 }
209 _timeout.setInterval(_effectiveTimeout());
210 _timeout.start();
211 qCDebug(SigningControllerLog) << "[ch" << _mavlinkChannel << "] disable pending — sysid" << expectedSysId
212 << "timeout" << kTimeout << "ms";
213 return std::nullopt;
214}
215
216bool SigningController::processFrame(bool framingOk, const mavlink_message_t& message)
217{
218 if (_channel.consumeStatusTransition(_mavlinkChannel)) {
219 QMetaObject::invokeMethod(this, [this]() { emit stateChanged(); }, Qt::AutoConnection);
220 }
221
222 if (!framingOk) {
223 MAVLinkSigning::logSigningFailure(_mavlinkChannel);
224 bool burstFired = false;
225 uint8_t burstCount = 0;
226 bool pendingEnable = false;
227 {
228 QMutexLocker<QRecursiveMutex> locker(&_fsmMutex);
229 burstFired = _badSigBurst.record();
230 burstCount = _badSigBurst.count();
231 pendingEnable = (_op.kind == OpKind::Enable);
232 }
233 if (burstFired) {
234 // Pending-enable burst: user is staring at "Configuring…"; tell them it's a key mismatch.
235 const QString detail =
236 pendingEnable
237 ? tr("MAVLink signing: %1 consecutive bad signatures while enabling — the chosen key likely "
238 "does not match the vehicle's stored key. Verify the key on the vehicle, then retry.")
239 .arg(burstCount)
240 : tr("MAVLink signing: %1 consecutive bad signatures on this link — wrong key or vehicle clock "
241 "drift")
242 .arg(burstCount);
243 QMetaObject::invokeMethod(this, [this, detail]() { emit alertRaised(detail); }, Qt::AutoConnection);
244 }
245 return false;
246 }
247
248 {
249 QMutexLocker<QRecursiveMutex> locker(&_fsmMutex);
250 _badSigBurst.reset();
251 }
252
253 bool autoDetected = false;
254 if (MAVLinkSigning::isMessageSigned(message) && !_channel.isEnabled()) {
255 // Auto-detect bypasses the deferred-confirm FSM intentionally: tryDetectKey verifies the HMAC first, so the
256 // vehicle is provably already signing with this key.
257 const QString detected = MAVLinkSigningKeys::instance()->tryDetectKey(this, message);
258 if (!detected.isEmpty()) {
259 QMetaObject::invokeMethod(this, [this, detected]() { emit keyAutoDetected(detected); }, Qt::AutoConnection);
260 autoDetected = true;
261 }
262 }
263
264 {
265 QMutexLocker<QRecursiveMutex> locker(&_fsmMutex);
266 _handleFsmFrameLocked(message);
267 }
268
269 return autoDetected;
270}
271
273{
274 QMutexLocker<QRecursiveMutex> locker(&_fsmMutex);
275 _badSigBurst.reset();
276}
277
278void SigningController::_handleFsmFrameLocked(const mavlink_message_t& message)
279{
280 if (!_isPendingLocked()) {
281 return;
282 }
283 if (message.sysid != _op.expectedSysId) {
284 return;
285 }
286
287 // ERROR-severity STATUSTEXT mentioning "signing" → fast-fail (e.g. ArduPilot armed-rejection) before 5s timeout.
288 if (message.msgid == MAVLINK_MSG_ID_STATUSTEXT) {
289 mavlink_statustext_t st;
290 mavlink_msg_statustext_decode(&message, &st);
291 const QString text = QGCMAVLink::boundedStringField(st.text);
292 const bool errorSeverity = (st.severity <= MAV_SEVERITY_ERROR);
293 const bool mentionsSigning = text.contains(QLatin1String("signing"), Qt::CaseInsensitive);
294 if (errorSeverity && mentionsSigning) {
295 _failLocked(FailReason::InitFailed, tr("Vehicle rejected signing change: %1").arg(text));
296 return;
297 }
298 }
299
300 if (_op.kind == OpKind::Enable) {
301 if (message.msgid == MAVLINK_MSG_ID_HEARTBEAT && MAVLinkSigning::isMessageSigned(message)) {
302 // Defence-in-depth: re-verify against committed key so a future framing-error refactor can't confirm on the
303 // wrong key.
304 if (!MAVLinkSigning::verifySignature(_op.keyBytes, message)) {
305 qCWarning(SigningControllerLog)
306 << "[ch" << _mavlinkChannel
307 << "] pending-enable HEARTBEAT signature did not verify against committed key";
308 return;
309 }
310 _confirmLocked();
311 }
312 } else if (_op.kind == OpKind::Disable) {
313 if (!MAVLinkSigning::isMessageSigned(message) && message.msgid == MAVLINK_MSG_ID_HEARTBEAT) {
314 _op.unsignedSeen = true;
315 _confirmLocked();
316 }
317 }
318}
319
320void SigningController::_confirmLocked()
321{
322 // QTimer::stop is not thread-safe; route through queued invoke since processFrame may run on link thread.
323 QMetaObject::invokeMethod(&_timeout, "stop", Qt::AutoConnection);
324
325 if (_op.kind == OpKind::Enable) {
326 const QString confirmedName = _op.keyName;
327 if (!_channel.setSignOutgoing(true) || !_channel.setAcceptUnsignedCallback(MAVLinkSigning::callbackForPolicy(
329 const QString detail = tr("Signing confirmation received but local activation failed");
330 qCCritical(SigningControllerLog) << "[ch" << _mavlinkChannel << "]" << detail;
331 _failLocked(FailReason::InitFailed, detail);
332 return;
333 }
334 qCDebug(SigningControllerLog) << "[ch" << _mavlinkChannel << "] enable confirmed — key" << confirmedName;
335 _clearLocked();
336 QMetaObject::invokeMethod(
337 this, [this, confirmedName]() { emit signingConfirmed(confirmedName); }, Qt::AutoConnection);
338 } else if (_op.kind == OpKind::Disable) {
339 qCDebug(SigningControllerLog) << "[ch" << _mavlinkChannel << "] disable confirmed";
340 _completeDisableSuccessLocked();
341 }
342}
343
344void SigningController::_completeDisableSuccessLocked()
345{
346 _channel.init(_mavlinkChannel, QByteArrayView(), nullptr);
347 _clearLocked();
348 QMetaObject::invokeMethod(this, [this]() { emit signingConfirmed(QString{}); }, Qt::AutoConnection);
349}
350
351void SigningController::_failLocked(FailReason reason, const QString& detail, bool cancelled)
352{
353 QMetaObject::invokeMethod(&_timeout, "stop", Qt::AutoConnection);
354
355 // Disable: if vehicle already sent an unsigned heartbeat before timeout/cancel, treat as success.
356 if (_op.kind == OpKind::Disable && _op.unsignedSeen && !cancelled) {
357 _completeDisableSuccessLocked();
358 return;
359 }
360
361 FailReason effectiveReason = reason;
362 QString effectiveDetail = detail;
363
364 if (_op.kind == OpKind::Enable) {
365 _channel.init(_mavlinkChannel, QByteArrayView(), nullptr);
366 } else if (_op.kind == OpKind::Disable) {
367 _channel.setAcceptUnsignedCallback(
369 effectiveReason = FailReason::VehicleUnreachable;
370 effectiveDetail =
371 tr("Signing disable not confirmed — vehicle is unreachable or still requires signed messages. Local "
372 "signing remains enabled.");
373 }
374
375 qCWarning(SigningControllerLog) << "[ch" << _mavlinkChannel
376 << "] signing operation failed:" << failReasonName(effectiveReason)
377 << effectiveDetail;
378
379 SigningFailure failure{effectiveReason, effectiveDetail};
380 _clearLocked();
381 QMetaObject::invokeMethod(this, [this, failure]() { emit signingFailed(failure); }, Qt::AutoConnection);
382}
383
384void SigningController::cancelPending(const QString& detail)
385{
386 QMutexLocker<QRecursiveMutex> locker(&_fsmMutex);
387 if (!_isPendingLocked()) {
388 return;
389 }
390 const QString effectiveDetail =
391 detail.isEmpty()
392 ? tr("Signing operation cancelled — primary link changed before vehicle confirmation")
393 : detail;
394 _failLocked(FailReason::VehicleUnreachable, effectiveDetail, /*cancelled=*/true);
395}
396
397void SigningController::_onTimeout()
398{
399 QMutexLocker<QRecursiveMutex> locker(&_fsmMutex);
400 if (!_isPendingLocked()) {
401 return;
402 }
403 qCDebug(SigningControllerLog) << "[ch" << _mavlinkChannel << "] timeout fired —"
404 << (_op.kind == OpKind::Enable ? "enable" : "disable") << "not confirmed";
405 const QString detail = (_op.kind == OpKind::Enable) ? tr("Signing setup not confirmed by vehicle (timeout)")
406 : tr("Signing disable not confirmed by vehicle (timeout)");
407 _failLocked(FailReason::Timeout, detail);
408}
409
410void SigningController::_clearLocked()
411{
412 _autoDetectGuard.reset();
413 QGC::secureZero(_op.keyBytes);
414 _setOpLocked(PendingOp{});
415 // Common FSM exit: enable-confirm leaves the channel signing (keep), disable/abort disables it (stop).
416 _setWallClockRefresh(_channel.isEnabled());
417}
mavlink_channel_t
struct __mavlink_message mavlink_message_t
#define QGC_LOGGING_CATEGORY(name, categoryStr)
static MAVLinkSigningKeys * instance()
void recordTimestamp(const QString &name, uint64_t ts)
Update in-memory + persisted last-timestamp for name. Monotonic — older values are dropped.
QString tryDetectKey(SigningController *controller, const mavlink_message_t &message)
Try every stored key against message's signature; on match, configures channel and returns the key na...
uint64_t lastTimestamp(const QString &name) const
Last persisted signing timestamp for name, or 0 if unknown / no entry.
void signingConfirmed(const QString &keyName)
Emitted exactly once per begin*() on success. keyName is the enabled key, or empty for disable.
SigningController(mavlink_channel_t channel, QObject *parent=nullptr)
SigningStatus::State State
std::optional< SigningFailure > tryBeginEnable(quint32 expectedSysId, const QString &keyName, const MAVLinkSigning::SigningKey &keyBytes)
Begin pending-enable. Caller must send SETUP_SIGNING only on nullopt; outcome arrives via signingConf...
QString keyName() const
bool initSigningImmediate(QByteArrayView key, MAVLinkSigning::UnsignedAcceptancePolicy policy, const QString &keyNameHint={})
Bypasses the FSM; used by tests and auto-detect. Non-empty keyNameHint seeds the persisted timestamp.
bool processFrame(bool framingOk, const mavlink_message_t &message)
Per-frame entry point; drives burst alerts, auto-detect, and the FSM. Returns true on auto-detect.
QString statusText() const
SigningFailure::Reason FailReason
void cancelPending(const QString &detail={})
void alertRaised(const QString &detail)
~SigningController() override
SigningStatus status() const
void keyAutoDetected(const QString &keyName)
void signingFailed(SigningFailure failure)
Emitted exactly once per begin*() on failure (timeout, init error, cancel, re-entry).
const SigningChannel & channel() const
std::optional< SigningFailure > tryBeginDisable(quint32 expectedSysId)
Atomic check-and-commit for disable; same contract as tryBeginEnable.
Reason a signing operation failed. Used by SigningController error path and Vehicle::signingFailed.
QString signingStatusString(mavlink_channel_t channel)
bool verifySignature(QByteArrayView key, const mavlink_message_t &message)
Verify a key against a signed message's signature.
bool isMessageSigned(const mavlink_message_t &message)
Returns true if the message has a MAVLink2 signature.
mavlink_accept_unsigned_t callbackForPolicy(UnsignedAcceptancePolicy policy)
Maps a high-level policy to the underlying libmavlink callback.
void logSigningFailure(mavlink_channel_t channel)
std::array< uint8_t, kSigningKeySize > SigningKey
std::array avoids QByteArray COW detach so secureZero() actually wipes the bytes.
void secureZero(void *data, size_t size)
QString statusText