mavlink_core/signing.rs
1use crate::{MAVLinkV2MessageRaw, consts};
2
3use std::time::SystemTime;
4use std::{collections::HashMap, fmt, sync::Mutex};
5
6use zeroize::Zeroizing;
7
8/// Configuration used for MAVLink 2 messages signing as defined in <https://mavlink.io/en/guide/message_signing.html>.
9///
10/// To use a [`SigningConfig`] for sending and reciving messages create a [`SigningData`] object using `SigningData::from_config`.
11///
12/// Debug output redacts the secret key.
13///
14/// # Key handling
15///
16/// This configuration implements neither [`Copy`] nor [`Clone`]. The owned secret
17/// key is zeroized when this configuration is dropped.
18///
19/// This does not erase copies retained by the caller or guarantee erasure of
20/// temporary copies created by moves. Zeroization requires destructors to run,
21/// so it does not occur if they are skipped, for example on process abort or when
22/// the configuration is intentionally leaked with [`std::mem::forget`] or [`Box::leak`].
23///
24/// # Examples
25/// Creating `SigningData`:
26/// ```
27/// # use mavlink_core::{SigningData, SigningConfig};
28/// let config = SigningConfig::new([0u8; 32], 0, true, false);
29/// let sign_data = SigningData::from_config(config);
30/// ```
31///
32/// `SigningConfig` does not implement `Clone`:
33/// ```compile_fail
34/// # use mavlink_core::SigningConfig;
35/// fn requires_clone<T: Clone>() {}
36/// requires_clone::<SigningConfig>();
37/// ```
38pub struct SigningConfig {
39 secret_key: Zeroizing<[u8; 32]>,
40 link_id: u8,
41 pub(crate) sign_outgoing: bool,
42 pub(crate) allow_unsigned: bool,
43}
44
45impl fmt::Debug for SigningConfig {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 f.debug_struct("SigningConfig")
48 .field("secret_key", &"[REDACTED]")
49 .field("link_id", &self.link_id)
50 .field("sign_outgoing", &self.sign_outgoing)
51 .field("allow_unsigned", &self.allow_unsigned)
52 .finish()
53 }
54}
55
56// mutable state of signing per connection
57pub(crate) struct SigningState {
58 timestamp: u64,
59 stream_timestamps: HashMap<(u8, u32, u8), u64>,
60}
61
62/// MAVLink 2 message signing data
63///
64/// Contains a [`SigningConfig`] as well as a mutable state that is reused for all messages in a connection.
65pub struct SigningData {
66 pub(crate) config: SigningConfig,
67 pub(crate) state: Mutex<SigningState>,
68}
69
70impl SigningConfig {
71 /// Creates a new signing configuration.
72 ///
73 /// If `sign_outgoing` is set messages send using this configuration will be signed.
74 /// If `allow_unsigned` is set, when receiving messages, all unsigned messages are accepted, this may also includes MAVLink 1 messages.
75 ///
76 /// The key is stored in an owned buffer that is zeroized on drop. Since `[u8; 32]` is `Copy`, callers remain responsible for clearing
77 /// their own copies.
78 pub fn new(
79 secret_key: [u8; 32],
80 link_id: u8,
81 sign_outgoing: bool,
82 allow_unsigned: bool,
83 ) -> Self {
84 Self {
85 secret_key: Zeroizing::new(secret_key),
86 link_id,
87 sign_outgoing,
88 allow_unsigned,
89 }
90 }
91}
92
93impl SigningData {
94 /// Initializes signing data from a given [`SigningConfig`]
95 pub fn from_config(config: SigningConfig) -> Self {
96 Self {
97 config,
98 state: Mutex::new(SigningState {
99 timestamp: 0,
100 stream_timestamps: HashMap::new(),
101 }),
102 }
103 }
104
105 /// Verify the signature of a MAVLink 2 message.
106 ///
107 /// This respects the `allow_unsigned` parameter in [`SigningConfig`].
108 pub fn verify_signature(&self, message: &MAVLinkV2MessageRaw) -> bool {
109 if message.incompatibility_flags() & consts::v2::IFLAG_SIGNED > 0 {
110 // The code that holds the mutex lock is not expected to panic, therefore the expect is justified.
111 // The only issue that might cause a panic, presuming the opertions on the message buffer are sound,
112 // is the `SystemTime::now()` call in `get_current_timestamp()`.
113 let mut state = self
114 .state
115 .lock()
116 .expect("Code holding MutexGuard should not panic.");
117 state.timestamp = u64::max(state.timestamp, Self::get_current_timestamp());
118 let timestamp = message.signature_timestamp();
119 let src_system = message.system_id();
120 let src_component = message.component_id();
121 let stream_key = (message.signature_link_id(), src_system, src_component);
122 match state.stream_timestamps.get(&stream_key) {
123 Some(stream_timestamp) => {
124 if timestamp <= *stream_timestamp {
125 // reject old timestamp
126 return false;
127 }
128 }
129 None => {
130 if timestamp + 60 * 1000 * 100 < state.timestamp {
131 // bad new stream, more then a minute older the the last one
132 return false;
133 }
134 }
135 }
136
137 let mut signature_buffer = [0u8; consts::v2::SIGNATURE_VALUE_SIZE];
138 message.calculate_signature(self.config.secret_key.as_ref(), &mut signature_buffer);
139 let result = signature_buffer == message.signature_value();
140 if result {
141 // if signature is valid update timestamps
142 state.stream_timestamps.insert(stream_key, timestamp);
143 state.timestamp = u64::max(state.timestamp, timestamp);
144 }
145 result
146 } else {
147 self.config.allow_unsigned
148 }
149 }
150
151 /// Sign a MAVLink 2 message if its incompatibility flag is set accordingly.
152 pub fn sign_message(&self, message: &mut MAVLinkV2MessageRaw) {
153 if message.incompatibility_flags() & consts::v2::IFLAG_SIGNED > 0 {
154 // The code that holds the mutex lock is not expected to panic, therefore the expect is justified.
155 // The only issue that might cause a panic, presuming the opertions on the message buffer are sound,
156 // is the `SystemTime::now()` call in `get_current_timestamp()`.
157 let mut state = self
158 .state
159 .lock()
160 .expect("Code holding MutexGuard should not panic.");
161 state.timestamp = u64::max(state.timestamp, Self::get_current_timestamp());
162 let ts_bytes = u64::to_le_bytes(state.timestamp);
163 message
164 .signature_timestamp_bytes_mut()
165 .copy_from_slice(&ts_bytes[0..consts::v2::SIGNATURE_TIMESTAMP_SIZE]);
166 *message.signature_link_id_mut() = self.config.link_id;
167
168 let mut signature_buffer = [0u8; consts::v2::SIGNATURE_VALUE_SIZE];
169 message.calculate_signature(self.config.secret_key.as_ref(), &mut signature_buffer);
170
171 message
172 .signature_value_mut()
173 .copy_from_slice(&signature_buffer);
174 state.timestamp += 1;
175 }
176 }
177
178 fn get_current_timestamp() -> u64 {
179 // fallback to 0 if the system time appears to be before epoch
180 let now = SystemTime::now()
181 .duration_since(SystemTime::UNIX_EPOCH)
182 .map(|n| n.as_micros())
183 .unwrap_or(0);
184 // use 1st January 2015 GMT as offset, fallback to 0 if before that date, the used 48 bit of this will overflow in 2104
185 (now.saturating_sub(1420070400u128 * 1000000u128) / 10u128) as u64
186 }
187}
188
189#[cfg(test)]
190mod tests {
191 use super::SigningConfig;
192
193 #[test]
194 fn debug_redacts_secret_key() {
195 let config = SigningConfig::new([0; 32], 7, true, false);
196 let other_key = SigningConfig::new([255; 32], 7, true, false);
197
198 let debug = format!("{config:?}");
199 assert_eq!(debug, format!("{other_key:?}"));
200 assert_eq!(
201 debug,
202 r#"SigningConfig { secret_key: "[REDACTED]", link_id: 7, sign_outgoing: true, allow_unsigned: false }"#,
203 );
204 assert_eq!(format!("{config:#?}"), format!("{other_key:#?}"));
205 }
206}