1use super::{ECDSA_PLAIN_SHA256_OID, ParseError, SignatureWidth, parse};
12use alloc::collections::VecDeque;
13use core::{fmt, num::NonZeroU8, time::Duration};
14pub use smgw_sec::BrainpoolP256Verifier;
15
16#[cfg(feature = "wakeup-store")]
17mod store;
18
19#[derive(Debug)]
21#[non_exhaustive]
22pub enum VerifyError<E> {
23 Parse(ParseError),
25 InvalidRecipientId,
27 Recipient,
29 Algorithm,
31 Freshness,
33 Replay,
35 ClockRegression,
37 RateLimited,
39 Signature,
41 #[cfg(feature = "wakeup-store")]
43 StoreAlreadyConfigured,
44 #[cfg(feature = "wakeup-store")]
46 Store(redb::Error),
47 Crypto(E),
49}
50
51impl<E: fmt::Display> fmt::Display for VerifyError<E> {
52 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53 f.write_str(match self {
54 Self::Parse(e) => return e.fmt(f),
55 Self::InvalidRecipientId => "invalid configured gateway identifier",
56 Self::Recipient => "unexpected management recipient",
57 Self::Algorithm => "unsupported management signature algorithm",
58 Self::Freshness => "management timestamp outside the freshness window",
59 Self::Replay => "management timestamp already accepted or superseded",
60 Self::ClockRegression => "monotonic time moved backwards",
61 Self::RateLimited => "management signature verification budget exhausted",
62 Self::Signature => "invalid management signature",
63 #[cfg(feature = "wakeup-store")]
64 Self::StoreAlreadyConfigured => "a replay database is already configured",
65 #[cfg(feature = "wakeup-store")]
66 Self::Store(redb::Error::WouldBlock) => "wake-up replay database writer is busy",
67 #[cfg(feature = "wakeup-store")]
68 Self::Store(e) => return write!(f, "wake-up replay database: {e}"),
69 Self::Crypto(e) => return e.fmt(f),
70 })
71 }
72}
73
74impl<E: core::error::Error + 'static> core::error::Error for VerifyError<E> {
75 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
76 match self {
77 Self::Parse(e) => Some(e),
78 #[cfg(feature = "wakeup-store")]
79 Self::Store(e) => Some(e),
80 Self::Crypto(e) => Some(e),
81 _ => None,
82 }
83 }
84}
85
86pub struct WakeUpVerifier<V> {
105 recipient: [u8; 9],
106 key: V,
107 budget: NonZeroU8,
108 attempts: VecDeque<Duration>,
109 last_monotonic: Duration,
110 last_accepted: Option<i64>,
111 #[cfg(feature = "wakeup-store")]
112 store: Option<store::ReplayStore>,
113}
114
115impl<V: BrainpoolP256Verifier> WakeUpVerifier<V> {
116 pub fn new(
119 recipient: [u8; 9],
120 key: V,
121 attempts_per_minute: NonZeroU8,
122 ) -> Result<Self, VerifyError<V::Error>> {
123 if !super::valid_recipient(&recipient) {
124 return Err(VerifyError::InvalidRecipientId);
125 }
126 Ok(Self {
127 recipient,
128 key,
129 budget: attempts_per_minute,
130 attempts: VecDeque::with_capacity(usize::from(attempts_per_minute.get())),
131 last_monotonic: Duration::ZERO,
132 last_accepted: None,
133 #[cfg(feature = "wakeup-store")]
134 store: None,
135 })
136 }
137
138 #[cfg(feature = "wakeup-store")]
150 pub fn with_replay_database(
151 mut self,
152 path: impl AsRef<std::path::Path>,
153 ) -> Result<Self, VerifyError<V::Error>> {
154 if self.store.is_some() {
155 return Err(VerifyError::StoreAlreadyConfigured);
156 }
157 let store = store::ReplayStore::open(path.as_ref()).map_err(VerifyError::Store)?;
158 if let Some(timestamp) = self.last_accepted {
159 store
160 .advance(&self.recipient, timestamp)
161 .map_err(VerifyError::Store)?;
162 }
163 self.last_accepted = store
164 .watermark(&self.recipient)
165 .map_err(VerifyError::Store)?;
166 self.store = Some(store);
167 Ok(self)
168 }
169
170 pub fn verify(
173 &mut self,
174 packet: &[u8],
175 synchronized_unix_seconds: i64,
176 monotonic: Duration,
177 ) -> Result<i64, VerifyError<V::Error>> {
178 if monotonic < self.last_monotonic {
179 return Err(VerifyError::ClockRegression);
180 }
181 self.last_monotonic = monotonic;
182 let message = parse(packet, SignatureWidth::Bits256).map_err(VerifyError::Parse)?;
183 if message.recipient_id != &self.recipient {
184 return Err(VerifyError::Recipient);
185 }
186 if message.algorithm_oid != ECDSA_PLAIN_SHA256_OID {
187 return Err(VerifyError::Algorithm);
188 }
189 if self
190 .last_accepted
191 .is_some_and(|t| message.unix_seconds <= t)
192 {
193 return Err(VerifyError::Replay);
194 }
195 if message.unix_seconds.abs_diff(synchronized_unix_seconds) >= 30 {
196 return Err(VerifyError::Freshness);
197 }
198 while self
199 .attempts
200 .front()
201 .is_some_and(|t| monotonic - *t >= Duration::from_secs(60))
202 {
203 self.attempts.pop_front();
204 }
205 if self.attempts.len() == usize::from(self.budget.get()) {
206 return Err(VerifyError::RateLimited);
207 }
208 self.attempts.push_back(monotonic);
209 let r = message
210 .r
211 .try_into()
212 .map_err(|_| VerifyError::Parse(ParseError::Length))?;
213 let s = message
214 .s
215 .try_into()
216 .map_err(|_| VerifyError::Parse(ParseError::Length))?;
217 if !self
218 .key
219 .verify(message.signed_bytes, r, s)
220 .map_err(VerifyError::Crypto)?
221 {
222 return Err(VerifyError::Signature);
223 }
224 #[cfg(feature = "wakeup-store")]
225 if let Some(store) = &self.store
226 && !store
227 .advance(&self.recipient, message.unix_seconds)
228 .map_err(VerifyError::Store)?
229 {
230 return Err(VerifyError::Replay);
231 }
232 self.last_accepted = Some(message.unix_seconds);
233 Ok(message.unix_seconds)
234 }
235}
236
237#[cfg(test)]
238mod tests {
239 use super::*;
240 use openssl::ec::{EcGroup, EcKey};
241 use openssl::sign::Signer;
242 use openssl::{
243 ecdsa::EcdsaSig,
244 hash::MessageDigest,
245 nid::Nid,
246 pkey::{PKey, Private},
247 };
248 use smgw_sec::openssl::BrainpoolP256PublicKey;
249
250 const RECIPIENT: [u8; 9] = *b"\x0eTST\x00\x00\x00\x00\x01";
251 const NOW: i64 = 1_700_000_000;
252 const ZERO: Duration = Duration::ZERO;
253
254 fn key(curve: Nid) -> PKey<Private> {
255 let group = EcGroup::from_curve_name(curve).unwrap();
256 PKey::from_ec_key(EcKey::generate(&group).unwrap()).unwrap()
257 }
258
259 fn public(key: &PKey<Private>) -> BrainpoolP256PublicKey {
260 BrainpoolP256PublicKey::from_pem(&key.public_key_to_pem().unwrap()).unwrap()
261 }
262
263 fn verifier(key: &PKey<Private>, budget: u8) -> WakeUpVerifier<BrainpoolP256PublicKey> {
264 WakeUpVerifier::new(RECIPIENT, public(key), NonZeroU8::new(budget).unwrap()).unwrap()
265 }
266
267 fn signed_fixture(key: &PKey<Private>, timestamp: i64) -> [u8; 108] {
268 signed_for_recipient(key, timestamp, RECIPIENT)
269 }
270
271 fn signed_for_recipient(key: &PKey<Private>, timestamp: i64, recipient: [u8; 9]) -> [u8; 108] {
272 let mut packet = [0; 108];
273 packet[..3].copy_from_slice(b"WU\x01");
274 packet[3..12].copy_from_slice(&recipient);
275 packet[12..20].copy_from_slice(×tamp.to_le_bytes());
276 packet[20..32].fill(11);
277 packet[32..34].copy_from_slice(&[1, 10]);
278 packet[34..44].copy_from_slice(ECDSA_PLAIN_SHA256_OID);
279 let mut signer = Signer::new(MessageDigest::sha256(), key).unwrap();
280 let signature =
281 EcdsaSig::from_der(&signer.sign_oneshot_to_vec(&packet[..32]).unwrap()).unwrap();
282 packet[44..76].copy_from_slice(&signature.r().to_vec_padded(32).unwrap());
283 packet[76..].copy_from_slice(&signature.s().to_vec_padded(32).unwrap());
284 packet
285 }
286
287 #[test]
288 fn constructor_rejects_invalid_configured_recipient() {
289 let public_key = public(&key(Nid::BRAINPOOL_P256R1));
290 let mut upper_bound = RECIPIENT;
291 upper_bound[4] = 0xfe;
292 upper_bound[5..].copy_from_slice(&99_999_999_u32.to_be_bytes());
293 assert!(WakeUpVerifier::new(upper_bound, public_key.clone(), NonZeroU8::MIN).is_ok());
294 let mut out_of_range = upper_bound;
295 out_of_range[5..].copy_from_slice(&100_000_000_u32.to_be_bytes());
296 for invalid in [
297 [0; 9],
298 *b"\x0eTsT\x00\x00\x00\x00\x01",
299 *b"\x0eTST\xff\x00\x00\x00\x01",
300 out_of_range,
301 ] {
302 assert!(matches!(
303 WakeUpVerifier::new(invalid, public_key.clone(), NonZeroU8::MIN),
304 Err(VerifyError::InvalidRecipientId)
305 ));
306 }
307 }
308
309 #[test]
310 fn validates_brainpool_signature_and_binds_signed_content() {
311 let signer = key(Nid::BRAINPOOL_P256R1);
312 let mut validator = verifier(&signer, 4);
313 let fixture = signed_fixture(&signer, NOW);
314 let mut altered = fixture;
315 altered[12] ^= 1;
316 assert!(matches!(
317 validator.verify(&altered, NOW, ZERO),
318 Err(VerifyError::Signature)
319 ));
320 let other_signer = signed_fixture(&key(Nid::BRAINPOOL_P256R1), NOW);
321 assert!(matches!(
322 validator.verify(&other_signer, NOW, ZERO),
323 Err(VerifyError::Signature)
324 ));
325 assert_eq!(validator.verify(&fixture, NOW, ZERO).unwrap(), NOW);
326 }
327
328 #[test]
329 fn provider_failure_consumes_an_attempt_without_advancing_replay() {
330 struct Recovering {
332 key: BrainpoolP256PublicKey,
333 first_call: bool,
334 }
335
336 impl BrainpoolP256Verifier for Recovering {
337 type Error = core::fmt::Error;
338
339 fn verify(
340 &mut self,
341 message: &[u8],
342 r: &[u8; 32],
343 s: &[u8; 32],
344 ) -> Result<bool, Self::Error> {
345 if core::mem::take(&mut self.first_call) {
346 return Err(core::fmt::Error);
347 }
348 self.key.verify(message, r, s).map_err(|_| core::fmt::Error)
349 }
350 }
351
352 let signer = key(Nid::BRAINPOOL_P256R1);
353 let packet = signed_fixture(&signer, NOW);
354 let provider = Recovering {
355 key: public(&signer),
356 first_call: true,
357 };
358 let mut verifier = WakeUpVerifier::new(RECIPIENT, provider, NonZeroU8::MIN).unwrap();
359 assert!(matches!(
360 verifier.verify(&packet, NOW, ZERO),
361 Err(VerifyError::Crypto(_))
362 ));
363 assert!(matches!(
364 verifier.verify(&packet, NOW, ZERO),
365 Err(VerifyError::RateLimited)
366 ));
367 let later = Duration::from_secs(60);
368 assert_eq!(verifier.verify(&packet, NOW, later).unwrap(), NOW);
369 assert!(matches!(
370 verifier.verify(&packet, NOW, later),
371 Err(VerifyError::Replay)
372 ));
373 }
374
375 #[test]
376 fn freshness_checks_bounds_and_extreme_timestamps_without_consuming_budget() {
377 let signer = key(Nid::BRAINPOOL_P256R1);
378 for delta in [-31, -30, -29, 0, 29, 30, 31] {
379 let mut validator = verifier(&signer, 1);
380 let result = validator.verify(&signed_fixture(&signer, NOW + delta), NOW, ZERO);
381 if (-29..=29).contains(&delta) {
382 assert_eq!(result.unwrap(), NOW + delta);
383 } else {
384 assert!(matches!(result, Err(VerifyError::Freshness)));
385 }
386 }
387 let mut validator = verifier(&signer, 1);
388 assert!(matches!(
389 validator.verify(&signed_fixture(&signer, i64::MIN), i64::MAX, ZERO),
390 Err(VerifyError::Freshness)
391 ));
392 let fixture = signed_fixture(&signer, NOW);
393 let mut wrong = fixture;
394 wrong[11] ^= 1;
395 assert!(matches!(
396 validator.verify(&wrong, NOW, ZERO),
397 Err(VerifyError::Recipient)
398 ));
399 wrong = fixture;
400 wrong[43] ^= 1;
401 assert!(matches!(
402 validator.verify(&wrong, NOW, ZERO),
403 Err(VerifyError::Algorithm)
404 ));
405 assert!(validator.verify(&[], NOW, ZERO).is_err());
406 assert_eq!(validator.verify(&fixture, NOW, ZERO).unwrap(), NOW);
407 }
408
409 #[test]
410 fn replay_survives_wall_rollback_and_re_signing() {
411 let signer = key(Nid::BRAINPOOL_P256R1);
412 let mut validator = verifier(&signer, 2);
413 let timestamp = signed_fixture(&signer, NOW);
414 validator.verify(×tamp, NOW, ZERO).unwrap();
415 validator
416 .verify(&signed_fixture(&signer, NOW + 5), NOW + 5, ZERO)
417 .unwrap();
418 for replay in [
419 timestamp,
420 signed_fixture(&signer, NOW),
421 signed_fixture(&signer, NOW + 5),
422 ] {
423 assert!(matches!(
424 validator.verify(&replay, NOW, Duration::from_secs(61)),
425 Err(VerifyError::Replay)
426 ));
427 }
428 }
429
430 #[test]
431 fn rolling_minute_charges_invalid_signatures_and_rejects_monotonic_regression() {
432 let signer = key(Nid::BRAINPOOL_P256R1);
433 let mut validator = verifier(&signer, 2);
434 let valid = signed_fixture(&signer, NOW);
435 let invalid = signed_fixture(&key(Nid::BRAINPOOL_P256R1), NOW);
436 for t in [0, 30] {
437 assert!(matches!(
438 validator.verify(&invalid, NOW, Duration::from_secs(t)),
439 Err(VerifyError::Signature)
440 ));
441 }
442 assert!(matches!(
443 validator.verify(&valid, NOW, Duration::from_millis(59_999)),
444 Err(VerifyError::RateLimited)
445 ));
446 assert!(matches!(
447 validator.verify(&valid, NOW, ZERO),
448 Err(VerifyError::ClockRegression)
449 ));
450 assert!(matches!(
451 validator.verify(&invalid, NOW, Duration::from_secs(60)),
452 Err(VerifyError::Signature)
453 ));
454 assert!(matches!(
455 validator.verify(&valid, NOW, Duration::from_secs(61)),
456 Err(VerifyError::RateLimited)
457 ));
458 assert_eq!(
459 validator
460 .verify(&valid, NOW, Duration::from_secs(90))
461 .unwrap(),
462 NOW
463 );
464 }
465
466 #[cfg(feature = "wakeup-store")]
467 mod persistent {
468 use super::*;
469 use std::sync::{Arc, Barrier};
470
471 #[test]
472 fn restart_and_signer_rotation_preserve_only_the_intended_recipient() {
473 let dir = tempfile::tempdir().unwrap();
474 let path = dir.path().join("replay.redb");
475 let old = key(Nid::BRAINPOOL_P256R1);
476 let new = key(Nid::BRAINPOOL_P256R1);
477 let mut first = verifier(&old, 4).with_replay_database(&path).unwrap();
478 assert_eq!(
479 first.verify(&signed_fixture(&old, NOW), NOW, ZERO).unwrap(),
480 NOW
481 );
482 drop(first);
483 let mut rotated = verifier(&new, 4).with_replay_database(&path).unwrap();
484 for timestamp in [NOW - 1, NOW] {
485 assert!(matches!(
486 rotated.verify(&signed_fixture(&new, timestamp), NOW, ZERO),
487 Err(VerifyError::Replay)
488 ));
489 }
490 assert!(matches!(
491 rotated.verify(&signed_fixture(&old, NOW + 2), NOW, ZERO),
492 Err(VerifyError::Signature)
493 ));
494 assert_eq!(
495 rotated
496 .verify(&signed_fixture(&new, NOW + 1), NOW, ZERO)
497 .unwrap(),
498 NOW + 1
499 );
500 let mut next_recipient = RECIPIENT;
501 next_recipient[8] += 1;
502 let mut other = WakeUpVerifier::new(next_recipient, public(&new), NonZeroU8::MIN)
503 .unwrap()
504 .with_replay_database(path)
505 .unwrap();
506 assert_eq!(
507 other
508 .verify(&signed_for_recipient(&new, NOW, next_recipient), NOW, ZERO)
509 .unwrap(),
510 NOW
511 );
512 }
513
514 #[test]
515 fn competing_verifiers_commit_an_identical_timestamp_only_once() {
516 let dir = tempfile::tempdir().unwrap();
517 let path = dir.path().join("replay.redb");
518 let signer = key(Nid::BRAINPOOL_P256R1);
519 let packet = signed_fixture(&signer, NOW);
520 let ready = Arc::new(Barrier::new(2));
521 let worker = || {
522 let ready = Arc::clone(&ready);
523 let mut v = verifier(&signer, 2).with_replay_database(&path).unwrap();
524 std::thread::spawn(move || {
525 ready.wait();
526 match v.verify(&packet, NOW, ZERO) {
527 Ok(_) => true,
528 Err(VerifyError::Replay | VerifyError::Store(redb::Error::WouldBlock)) => {
529 false
530 }
531 Err(other) => panic!("{other}"),
532 }
533 })
534 };
535 let first = worker();
536 let second = worker();
537 assert_ne!(first.join().unwrap(), second.join().unwrap());
538 let mut reopened = verifier(&signer, 2).with_replay_database(&path).unwrap();
539 assert!(matches!(
540 reopened.verify(&packet, NOW, ZERO),
541 Err(VerifyError::Replay)
542 ));
543 }
544
545 #[test]
546 fn storage_failure_does_not_accept_or_poison_the_watermark() {
547 let dir = tempfile::tempdir().unwrap();
548 let path = dir.path().join("replay.redb");
549 let signer = key(Nid::BRAINPOOL_P256R1);
550 let packet = signed_fixture(&signer, NOW);
551 let mut v = verifier(&signer, 4).with_replay_database(&path).unwrap();
552 let peer = redb::Database::builder()
553 .set_concurrency_mode(redb::ConcurrencyMode::MultiWriter)
554 .create(&path)
555 .unwrap();
556 let lock = peer.begin_write().unwrap();
557 assert!(matches!(
558 v.verify(&packet, NOW, ZERO),
559 Err(VerifyError::Store(redb::Error::WouldBlock))
560 ));
561 lock.abort().unwrap();
562 assert_eq!(v.verify(&packet, NOW, ZERO).unwrap(), NOW);
563 assert!(matches!(
564 v.verify(&packet, NOW, ZERO),
565 Err(VerifyError::Replay)
566 ));
567 }
568
569 #[test]
570 fn attaching_after_acceptance_carries_history_and_rebinding_is_refused() {
571 let dir = tempfile::tempdir().unwrap();
572 let path = dir.path().join("replay.redb");
573 let signer = key(Nid::BRAINPOOL_P256R1);
574 let mut local = verifier(&signer, 2);
575 let packet = signed_fixture(&signer, NOW);
576 local.verify(&packet, NOW, ZERO).unwrap();
577 let persisted = local.with_replay_database(&path).unwrap();
578 let other_path = dir.path().join("different.redb");
579 assert!(matches!(
580 persisted.with_replay_database(&other_path),
581 Err(VerifyError::StoreAlreadyConfigured)
582 ));
583 assert!(!other_path.exists());
584 let mut restarted = verifier(&signer, 2).with_replay_database(path).unwrap();
585 assert!(matches!(
586 restarted.verify(&packet, NOW, ZERO),
587 Err(VerifyError::Replay)
588 ));
589 }
590
591 #[cfg(target_os = "linux")]
592 #[test]
593 fn non_utf8_paths_retain_history_across_reopen() {
594 use std::os::unix::ffi::OsStrExt;
595
596 let directory = tempfile::tempdir().unwrap();
597 let path = directory
598 .path()
599 .join(std::ffi::OsStr::from_bytes(b"history-\xff.redb"));
600 let signer = key(Nid::BRAINPOOL_P256R1);
601 let packet = signed_fixture(&signer, NOW);
602 let mut first = verifier(&signer, 1).with_replay_database(&path).unwrap();
603 assert_eq!(first.verify(&packet, NOW, ZERO).unwrap(), NOW);
604 drop(first);
605 let mut reopened = verifier(&signer, 1).with_replay_database(path).unwrap();
606 assert!(matches!(
607 reopened.verify(&packet, NOW, ZERO),
608 Err(VerifyError::Replay)
609 ));
610 }
611
612 #[test]
613 fn empty_unusable_and_corrupt_stores_fail_closed() {
614 let dir = tempfile::tempdir().unwrap();
615 let corrupt = dir.path().join("broken.redb");
616 std::fs::write(&corrupt, b"invalid replay database").unwrap();
617 let signer = key(Nid::BRAINPOOL_P256R1);
618 for path in [std::path::Path::new(""), dir.path(), &corrupt] {
619 assert!(
620 matches!(
621 verifier(&signer, 1).with_replay_database(path),
622 Err(VerifyError::Store(_))
623 ),
624 "{path:?}"
625 );
626 }
627 }
628 }
629}